How to CSS with Webpack 5 - Setup Tutorial

 by Robin Wieruch
 - Edit this Post

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

This tutorial is part 2 of 3 in 'Webpack with Font'-series.

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 a style loader to your dev dependencies:

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

And second, you can use both loaders for all CSS files in your Webpack configuration:

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

Then in a new src/style.css file, add some CSS to it:

h1 {
color: red;
}

And in your src/index.js file, or any other JS file, import this new CSS file:

import './style.css';

That's it. From here you can use CSS in your JavaScript project which is powered by Webpack.

CSS with Webpack in Production

If you happen to have a , you will need a different configuration for production when using CSS.

First, install the MiniCssExtractPlugin for Webpack to your dev dependencies:

npm install --save-dev mini-css-extract-plugin

And second, use it in your Webpack's production configuration instead of style loader and additionally as a plugin:

...
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: 'production',
module: {
rules: [
{
test: /\.(css)$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
],
},
],
},
plugins: [
new MiniCssExtractPlugin(),
...
],
...
};

That's it. Once you build your project with Webpack, you will see the style files showing up in your dist/ folder.

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

This tutorial is part 2 of 3 in 'Webpack with Font'-series.

Keep reading about 

So much has been said about the appropriate way to style modern web apps. There's the general and oldest method of styling at document level - creating a style.css file and linking to it in the HTML…

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.