PostCSS and autoprefixing (postcss-loader)

PostCSS and autoprefixing (postcss-loader)

PostCSS is a CSS post-processing tool that can transform your CSS in a lot of cool ways, like autoprefixing, linting and more!

First enable it in webpack.config.js:

  1. // webpack.config.js
  2. Encore
  3. // ...
  4. + .enablePostCssLoader()
  5. ;

Then restart Encore. When you do, it will give you a command you can run to install any missing dependencies. After running that command and restarting Encore, you’re done!

Next, download any plugins you want, like autoprefixer:

  1. $ yarn add autoprefixer --dev

Next, create a postcss.config.js file at the root of your project:

  1. module.exports = {
  2. plugins: {
  3. // include whatever plugins you want
  4. // but make sure you install these via yarn or npm!
  5. // add browserslist config to package.json (see below)
  6. autoprefixer: {}
  7. }
  8. }

That’s it! The postcss-loader will now be used for all CSS, Sass, etc files. You can also pass options to the postcss-loader by passing a callback:

  1. // webpack.config.js
  2. Encore
  3. // ...
  4. + .enablePostCssLoader((options) => {
  5. + options.config = {
  6. + // the directory where the postcss.config.js file is stored
  7. + path: 'path/to/config'
  8. + };
  9. + })
  10. ;

Adding browserslist to package.json

The autoprefixer (and many other tools) need to know what browsers you want to support. The best-practice is to configure this directly in your package.json (so that all the tools can read this):

  1. {
  2. + "browserslist": [
  3. + "defaults"
  4. + ]
  5. }

The defaults option is recommended for most users and would be equivalent to the following browserslist:

  1. {
  2. + "browserslist": [
  3. + "> 0.5%",
  4. + "last 2 versions",
  5. + "Firefox ESR",
  6. + "not dead"
  7. + ]
  8. }

See browserslist for more details on the syntax.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.