How to PostCSS with Webpack 5 - Setup Tutorial

Robin Wieruch

If you happen to have a custom Webpack setup, you may be wondering how to set up PostCSS with Webpack. This short tutorial walks you through the process. First of all, you need to install the PostCSS loader and a sensible PostCSS configuration to your dev dependencies:

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

Next, create a postcss.config.js file where you will reference all your PostCSS plugins. In this case, we will use the most commonly used PostCSS plugin called postcss-preset-env which enables sensible defaults:

javascript
module.exports = {
  plugins: [
    require('postcss-preset-env')({
      browsers: 'last 2 versions',
    }),
  ],
};

Last, use the PostCSS loader for all CSS (and SCSS, if you happen to have SASS too) files in your Webpack configuration:

javascript
...

module.exports = {
  ...
  module: {
    rules: [
      ...
      {
        test: /\.(scss|css)$/,
        use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'],
      },
    ],
  },
  ...
};

Now, if you are using CSS like the following, it will be automatically prefixed for certain browsers:

css
// before

.column {
  display: flex;
  flex-direction: column;
}

// after
.column {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
}

This is only one default coming with the PostCSS presets. You can explore more of them on their website or explore more PostCSS plugins.

Never Miss an Article

Join 50,000+ developers getting weekly insights on full-stack engineering and AI.

AI Agentic UI Architecture React Next.js TypeScript Node.js Full-Stack Monorepos Product Engineering
Subscribe on Substack

High signal, low noise. Unsubscribe at any time.