How to load CSS with Webpack

In our introduction to Webpack post, we saw What Webpack is, what it's used for and how to use it. We did all of this using a simple JS file that when processed with webpack generated a development version and a production version. However, what happens when we want to load CSS files? Today we will see how to make this possible.
The first thing you should do is install the following libraries.
npm i css-loader style-loader --save-dev
Once this is done, you should add the pattern that will read CSS files and use the loaders installed earlier. To do this, you must modify the webpack.config.js file and add a rule in module like this:
const path = require('path');
module.exports = {
entry: './main.js',
output: {
path: path.resolve(__dirname),
filename: 'app.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
],
}
}
Note that webpack's entry point is the main.js file. That being said, you can add something like the following in that file.
import './app.css'
After running the webpack command, you should get an output like the following:
Hash: d294dddeed23d606eb49
Version: webpack 4.44.2
Time: 788ms
Built at: 09/28/2020 11:06:42 PM
Asset Size Chunks Chunk Names
app.js 16.8 KiB main [emitted] main
Entrypoint main = app.js
[./app.css] 515 bytes {main} [built]
[./main.js] 121 bytes {main} [built]
[./node_modules/css-loader/dist/cjs.js!./app.css] 309 bytes {main} [built]
+ 2 hidden modules
This indicates that the CSS file has been loaded and is ready to be used with the output described in webpack. That is, you only need to worry about adding the app.js file and webpack will do the rest.