Convert Figma logo to code with AI

csstools logopostcss-preset-env

Convert modern CSS into something browsers understand

2,218
90
2,218
0

Top Related Projects

28,437

Transforming styles with JS plugins

43,380

The zero configuration build tool for the web. 📦🚀

CSS Loader

15,059

Sass makes CSS fun!

11,194

Expressive, robust, feature-rich CSS language built for nodejs

16,999

Less. The dynamic stylesheet language.

Quick Overview

PostCSS Preset Env is a PostCSS plugin that converts modern CSS into something most browsers can understand, determining the polyfills you need based on your targeted browsers. It allows you to use future CSS features today, providing a smooth transition as browsers implement new features.

Pros

  • Automatically polyfills CSS features based on browser support
  • Customizable with options to enable/disable specific features
  • Integrates seamlessly with existing PostCSS workflows
  • Regularly updated to support the latest CSS features

Cons

  • May increase bundle size due to added polyfills
  • Some complex CSS features might not be fully polyfillable
  • Learning curve for configuring and optimizing for specific browser targets
  • Potential performance impact for heavily polyfilled stylesheets

Code Examples

  1. Basic usage with default options:
const postcss = require('postcss');
const postcssPresetEnv = require('postcss-preset-env');

postcss([
  postcssPresetEnv()
]).process(yourCSS);
  1. Customizing features and stage:
postcss([
  postcssPresetEnv({
    stage: 3,
    features: {
      'nesting-rules': true,
      'custom-properties': false
    }
  })
]).process(yourCSS);
  1. Setting browser targets:
postcss([
  postcssPresetEnv({
    browsers: ['> 1%', 'last 2 versions', 'not dead']
  })
]).process(yourCSS);

Getting Started

To get started with PostCSS Preset Env:

  1. Install the package:

    npm install postcss postcss-preset-env --save-dev
    
  2. Create a PostCSS config file (e.g., postcss.config.js):

    module.exports = {
      plugins: [
        require('postcss-preset-env')({
          // Your options here
        })
      ]
    };
    
  3. Use it in your build process or with a PostCSS CLI tool.

For more detailed configuration options and usage instructions, refer to the official documentation.

Competitor Comparisons

28,437

Transforming styles with JS plugins

Pros of PostCSS

  • More flexible and customizable, allowing for a wider range of transformations
  • Lighter weight core with a plugin-based architecture
  • Faster processing times for large projects

Cons of PostCSS

  • Requires more setup and configuration to achieve similar functionality
  • Steeper learning curve for beginners
  • May need multiple plugins to replicate all features of postcss-preset-env

Code Comparison

PostCSS (with plugins):

module.exports = {
  plugins: [
    require('autoprefixer'),
    require('postcss-preset-env')({ stage: 3 }),
    require('cssnano')
  ]
}

postcss-preset-env:

module.exports = {
  plugins: [
    require('postcss-preset-env')({
      stage: 3,
      features: { 'nesting-rules': true }
    })
  ]
}

Summary

PostCSS offers more flexibility and customization options, making it suitable for complex projects with specific requirements. It provides a lightweight core that can be extended with plugins, resulting in faster processing times for large projects. However, it requires more setup and has a steeper learning curve.

postcss-preset-env, on the other hand, provides a more streamlined experience with pre-configured settings and features. It's easier to set up and use, especially for beginners, but may offer less flexibility for advanced use cases.

The choice between the two depends on project requirements, team expertise, and desired level of customization.

43,380

The zero configuration build tool for the web. 📦🚀

Pros of Parcel

  • Zero configuration bundler, offering a simpler setup process
  • Supports multiple file types out of the box (JS, CSS, HTML, images, etc.)
  • Faster build times due to multicore processing and caching

Cons of Parcel

  • Less granular control over the build process
  • May include unnecessary features for simpler projects
  • Potential for larger bundle sizes if not optimized properly

Code Comparison

PostCSS Preset Env:

const postcssPresetEnv = require('postcss-preset-env');

module.exports = {
  plugins: [
    postcssPresetEnv({
      stage: 3,
      features: {
        'nesting-rules': true
      }
    })
  ]
};

Parcel:

{
  "name": "my-project",
  "scripts": {
    "start": "parcel index.html",
    "build": "parcel build index.html"
  },
  "devDependencies": {
    "parcel": "^2.0.0"
  }
}

Summary

PostCSS Preset Env is a plugin for PostCSS that enables modern CSS features, while Parcel is a full-featured bundler. Parcel offers simplicity and out-of-the-box support for various file types, but may sacrifice fine-grained control. PostCSS Preset Env provides more specific CSS transformations but requires integration into a larger build process. The choice between them depends on project requirements and desired level of configuration.

CSS Loader

Pros of css-loader

  • Seamless integration with Webpack ecosystem
  • Handles CSS imports and url() resolving out of the box
  • Supports CSS Modules with minimal configuration

Cons of css-loader

  • Limited CSS processing capabilities without additional plugins
  • Doesn't provide automatic polyfilling for modern CSS features
  • Requires more setup for advanced CSS transformations

Code Comparison

css-loader configuration:

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
};

postcss-preset-env usage:

const postcssPresetEnv = require('postcss-preset-env');

module.exports = {
  plugins: [
    postcssPresetEnv({
      stage: 3,
      features: {
        'nesting-rules': true
      }
    })
  ]
};

Key Differences

postcss-preset-env focuses on providing a comprehensive set of CSS polyfills and transformations, allowing developers to use modern CSS features across different browsers. It's part of the PostCSS ecosystem and can be used independently of any bundler.

css-loader, on the other hand, is primarily designed to work within the Webpack ecosystem. It handles CSS file imports and resolves dependencies but doesn't provide extensive CSS processing capabilities on its own. For advanced CSS transformations, it often needs to be combined with other loaders or plugins.

While both tools serve different primary purposes, they can be used together in a Webpack setup to achieve both CSS importing and modern CSS feature support.

15,059

Sass makes CSS fun!

Pros of Sass

  • More mature and established ecosystem with extensive documentation and community support
  • Provides advanced features like mixins, functions, and control directives for complex styling logic
  • Offers a more intuitive and concise syntax for nested styles and variables

Cons of Sass

  • Requires compilation step, which can add complexity to the build process
  • Limited support for newer CSS features without additional tooling or updates
  • Syntax diverges from standard CSS, potentially making it harder for developers to switch between Sass and vanilla CSS

Code Comparison

Sass:

$primary-color: #3498db;

.button {
  background-color: $primary-color;
  &:hover { background-color: darken($primary-color, 10%); }
}

PostCSS Preset Env:

:root { --primary-color: #3498db; }

.button {
  background-color: var(--primary-color);
  &:hover { background-color: color-mod(var(--primary-color) shade(10%)); }
}

Key Differences

  • Sass uses its own syntax for variables and functions, while PostCSS Preset Env leverages native CSS custom properties and upcoming CSS features
  • PostCSS Preset Env focuses on future CSS compatibility, whereas Sass provides a more comprehensive styling language
  • Sass requires a specific compiler, while PostCSS Preset Env works within the PostCSS ecosystem, allowing for more flexible plugin configurations
11,194

Expressive, robust, feature-rich CSS language built for nodejs

Pros of Stylus

  • More concise syntax with optional colons, semicolons, and braces
  • Built-in functions and mixins for easier code reuse
  • Supports both indentation-based and CSS-like syntax

Cons of Stylus

  • Smaller community and ecosystem compared to PostCSS
  • Less focus on modern CSS features and polyfills
  • Steeper learning curve for developers familiar with standard CSS

Code Comparison

Stylus:

border-radius()
  -webkit-border-radius arguments
  -moz-border-radius arguments
  border-radius arguments

.button
  border-radius 5px

PostCSS Preset Env:

.button {
  border-radius: 5px;
}

Key Differences

Stylus is a preprocessor with its own syntax and features, while PostCSS Preset Env focuses on transforming modern CSS syntax into backwards-compatible CSS. Stylus offers more flexibility in writing styles but requires learning a new syntax. PostCSS Preset Env allows developers to use future CSS features today while maintaining compatibility with older browsers.

Stylus is better suited for projects where developers prefer a more expressive and concise syntax, while PostCSS Preset Env is ideal for teams that want to use cutting-edge CSS features without sacrificing browser support.

16,999

Less. The dynamic stylesheet language.

Pros of Less.js

  • Built-in features like variables, nesting, and mixins without additional plugins
  • Simpler setup and configuration for basic CSS preprocessing needs
  • Faster compilation times for smaller projects

Cons of Less.js

  • Limited future-proofing for upcoming CSS features
  • Fewer plugins and extensions compared to PostCSS ecosystem
  • Less active development and community support

Code Comparison

Less.js:

@primary-color: #007bff;

.button {
  background-color: @primary-color;
  &:hover {
    background-color: darken(@primary-color, 10%);
  }
}

PostCSS Preset Env:

:root {
  --primary-color: #007bff;
}

.button {
  background-color: var(--primary-color);
  &:hover {
    background-color: color-mod(var(--primary-color) shade(10%));
  }
}

Summary

Less.js offers a straightforward approach to CSS preprocessing with built-in features, making it easier to set up and use for simple projects. However, PostCSS Preset Env provides better future-proofing and a more extensive ecosystem of plugins. Less.js may be preferable for smaller projects or teams looking for a quick start, while PostCSS Preset Env is better suited for larger projects requiring more advanced features and long-term maintainability.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

⚠️ PostCSS Preset Env was moved to @csstools/postcss-plugins. ⚠️
Read the announcement

PostCSS Preset Env PostCSS

npm version build status support chat

PostCSS Preset Env lets you convert modern CSS into something most browsers can understand, determining the polyfills you need based on your targeted browsers or runtime environments.

npm install postcss-preset-env
@custom-media --viewport-medium (width <= 50rem);
@custom-selector :--heading h1, h2, h3, h4, h5, h6;

:root {
  --mainColor: #12345678;
}

body {
  color: var(--mainColor);
  font-family: system-ui;
  overflow-wrap: break-word;
}

:--heading {
  background-image: image-set(url(img/heading.png) 1x, url(img/heading@2x.png) 2x);

  @media (--viewport-medium) {
    margin-block: 0;
  }
}

a {
  color: rgb(0 0 100% / 90%);

  &:hover {
    color: rebeccapurple;
  }
}

/* becomes */

:root {
  --mainColor: rgba(18, 52, 86, 0.47059);
}

body {
  color: rgba(18, 52, 86, 0.47059);
  color: var(--mainColor);
  font-family: system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Droid Sans, Helvetica Neue;
  word-wrap: break-word;
}

h1, h2, h3, h4, h5, h6 {
  background-image: url(img/heading.png);
}

@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
  h1, h2, h3, h4, h5, h6 {
    background-image: url(img/heading@2x.png)
  }
}

@media (max-width: 50rem) {
  h1, h2, h3, h4, h5, h6 {
    margin-top: 0;
    margin-bottom: 0;
  }
}

a {
  color: rgba(0, 0, 255, 0.9)
}

a:hover {
  color: #639;
}

Without any configuration options, PostCSS Preset Env enables Stage 2 features and supports all browsers.

Transform with Preset Env Style with Preset Env

Usage

Add PostCSS Preset Env to your project:

npm install postcss-preset-env --save-dev

Use PostCSS Preset Env to process your CSS:

const postcssPresetEnv = require('postcss-preset-env');

postcssPresetEnv.process(YOUR_CSS /*, processOptions, pluginOptions */);

Or use it as a PostCSS plugin:

const postcss = require('postcss');
const postcssPresetEnv = require('postcss-preset-env');

postcss([
  postcssPresetEnv(/* pluginOptions */)
]).process(YOUR_CSS /*, processOptions */);

PostCSS Preset Env runs in all Node environments, with special instructions for:

NodePostCSS CLIWebpackCreate React AppGulpGruntRollup

Options

stage

The stage option determines which CSS features to polyfill, based upon their stability in the process of becoming implemented web standards.

postcssPresetEnv({ stage: 0 })

The stage can be 0 (experimental) through 4 (stable), or false. Setting stage to false will disable every polyfill. Doing this would only be useful if you intended to exclusively use the features option.

Without any configuration options, PostCSS Preset Env enables Stage 2 features.

features

The features option enables or disables specific polyfills by ID. Passing true to a specific feature ID will enable its polyfill, while passing false will disable it. List of IDs

postcssPresetEnv({
  /* use stage 3 features + css nesting rules */
  stage: 3,
  features: {
    'nesting-rules': true
  }
})

Passing an object to a specific feature ID will both enable and configure it.

postcssPresetEnv({
  /* use stage 3 features + css color-mod (warning on unresolved) */
  stage: 3,
  features: {
    'color-mod-function': { unresolved: 'warn' }
  }
})

Any polyfills not explicitly enabled or disabled through features are determined by the stage option.

browsers

The browsers option determines which polyfills are required based upon the browsers you are supporting.

PostCSS Preset Env supports any standard browserslist configuration, which can be a .browserslistrc file, a browserslist key in package.json, or browserslist environment variables.

The browsers option should only be used when a standard browserslist configuration is not available.

postcssPresetEnv({ browsers: 'last 2 versions' })

If not valid browserslist configuration is specified, the default browserslist query will be used.

insertBefore / insertAfter

The insertBefore and insertAfter keys allow you to insert other PostCSS plugins into the chain. This is only useful if you are also using sugary PostCSS plugins that must execute before or after certain polyfills. Both insertBefore and insertAfter support chaining one or multiple plugins.

import postcssSimpleVars from 'postcss-simple-vars';

postcssPresetEnv({
  insertBefore: {
    'all-property': postcssSimpleVars
  }
})

autoprefixer

PostCSS Preset Env includes autoprefixer and browsers option will be passed to it automatically.

Specifying the autoprefixer option enables passing additional options into autoprefixer.

postcssPresetEnv({
  autoprefixer: { grid: true }
})

Passing autoprefixer: false disables autoprefixer.

preserve

The preserve option determines whether all plugins should receive a preserve option, which may preserve or remove otherwise-polyfilled CSS. By default, this option is not configured.

postcssPresetEnv({
  preserve: false // instruct all plugins to omit pre-polyfilled CSS
});

importFrom

The importFrom option specifies sources where variables like Custom Media, Custom Properties, Custom Selectors, and Environment Variables can be imported from, which might be CSS, JS, and JSON files, functions, and directly passed objects.

postcssPresetEnv({
  /*
    @custom-media --small-viewport (max-width: 30em);
    @custom-selector :--heading h1, h2, h3;
    :root { --color: red; }
  */
  importFrom: 'path/to/file.css'
});

Multiple sources can be passed into this option, and they will be parsed in the order they are received. JavaScript files, JSON files, functions, and objects will use different namespaces to import different kinds of variables.

postcssPresetEnv({
  importFrom: [
    /*
      @custom-media --small-viewport (max-width: 30em);
      @custom-selector :--heading h1, h2, h3;
      :root { --color: red; }
    */
    'path/to/file.css',

    /* module.exports = {
      customMedia: { '--small-viewport': '(max-width: 30em)' },
      customProperties: { '--color': 'red' },
      customSelectors: { ':--heading': 'h1, h2, h3' },
      environmentVariables: { '--branding-padding': '20px' }
    } */
    'and/then/this.js',

    /* {
      "custom-media": { "--small-viewport": "(max-width: 30em)" }
      "custom-properties": { "--color": "red" },
      "custom-selectors": { ":--heading": "h1, h2, h3" },
      "environment-variables": { "--branding-padding": "20px" }
    } */
    'and/then/that.json',

    {
      customMedia: { '--small-viewport': '(max-width: 30em)' },
      customProperties: { '--color': 'red' },
      customSelectors: { ':--heading': 'h1, h2, h3' },
      environmentVariables: { '--branding-padding': '20px' }
    },
    () => {
      const customMedia = { '--small-viewport': '(max-width: 30em)' };
      const customProperties = { '--color': 'red' };
      const customSelectors = { ':--heading': 'h1, h2, h3' };
      const environmentVariables = { '--branding-padding': '20px' };

      return { customMedia, customProperties, customSelectors, environmentVariables };
    }
  ]
});

exportTo

The exportTo option specifies destinations where variables like Custom Media, Custom Properties, Custom Selectors, and Environment Variables can be exported to, which might be CSS, JS, and JSON files, functions, and directly passed objects.

postcssPresetEnv({
  /*
    @custom-media --small-viewport (max-width: 30em);
    @custom-selector :--heading h1, h2, h3;
    :root { --color: red; }
  */
  exportTo: 'path/to/file.css'
});

Multiple destinations can be passed into this option as well, and they will be parsed in the order they are received. JavaScript files, JSON files, and objects will use different namespaces to import different kinds of variables.

const cachedObject = {};

postcssPresetEnv({
  exportTo: [
    /*
      @custom-media --small-viewport (max-width: 30em);
      @custom-selector :--heading h1, h2, h3;
      :root { --color: red; }
    */
    'path/to/file.css',

    /* module.exports = {
      customMedia: { '--small-viewport': '(max-width: 30em)' },
      customProperties: { '--color': 'red' },
      customSelectors: { ':--heading': 'h1, h2, h3' },
      environmentVariables: { '--branding-padding': '20px' }
    } */
    'and/then/this.js',

    /* {
      "custom-media": { "--small-viewport": "(max-width: 30em)" }
      "custom-properties": { "--color": "red" },
      "custom-selectors": { ":--heading": "h1, h2, h3" },
      "environment-variables": { "--branding-padding": "20px" }
    } */
    'and/then/that.json',

    cachedObject,
    variables => {
      if ('customProperties' in variables) {
        // do something special with customProperties
      }

      Object.assign(cachedObject, variables);
    }
  ]
});

NPM DownloadsLast 30 Days