How to PostCSS with Webpack 5 - Setup Tutorial

 by Robin Wieruch
 - Edit this Post

This tutorial is part 4 of 4 in 'Webpack with Style'-series.

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:

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:

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:

...
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:

// 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.

Keep reading about 

If you happen to have a custom Webpack setup, you may be wondering how to set up CSS with Webpack. This short tutorial walks you through the process. First of all, you need to install a CSS loader and…

If you happen to have a custom Webpack setup, you may be wondering how to set up SASS with Webpack. This short tutorial walks you through the process. First of all, you need to install a SASS loader…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.