blog.jakoblind.no

How to configure PostCSS with webpack

What’s PostCSS

PostCSS takes your CSS file and runs plugins on it that can modify the CSS-rules or analyze your CSS file.

Post means after. PostCSS runs after CSS.

How to configure PostCSS with webpack

Step one is to configure CSS

The first thing we must do, before configuring PostCSS is to configure CSS in webpack. The reason is that PostCSS takes a CSS file as input.

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

And install the required NPM dependencies:

npm install --save-dev style-loader css-loader

Why do you need style-loader and css-loader? If you want to learn that and everything else there is to know about CSS config in webpack, like extracting the CSS to a separate file, or adding CSS modules, then read my article How to configure CSS and CSS modules in webpack

Ok, back to PostCSS.

After webpack has successfully processed your CSS file, you want to tell webpack to also run PostCSS on that CSS file. To do that you are going to use postcss-loader. Add it to the end of the list of loaders in your CSS config, like this:

 module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader',
          'postcss-loader'
        ]
      }
    ]
  }

and create a postcss.config.js file. it’s required to run post css. Let’s add the autoprefixer plugin to it, like this:

module.exports = {
  plugins: [
    require('autoprefixer')
  ]
};

And install the required dependencies:

npm install --save-dev autoprefixer postcss-loader

Now when you run webpack, PostCSS will be run on all your CSS files. Well, to be honest, almost all of your CSS file. If you import one CSS from your main CSS file with the @import keyword, webpack will not run postcss-loader on this imported file. Why? I don’t know. But I know how to fix it. Add importLoaders: 1 as an option to your css-loader, like this:

 module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1
            }
          },
          'postcss-loader'
        ]
      }
    ]
  }

If you just came here to copy/paste a simple PostCSS config with webpack, use this one above!

Now you have a complete PostCSS config set up with webpack! Nice! Now you can go ahead and add your PostCSS config that you want to use for your project in the postcss.config.js file. Good luck!


tags: