Lesson Weekend

In the last lesson, we bundled our JavaScript files with webpack. That's a good start - but we can also use webpack for bundling other files that aren't JavaScript. In this lesson, we'll learn how to bundle our CSS. Even though we'll only be working with one CSS file in our project, large scale projects often work with many CSS files, which means bundling them can make a noticeable difference in terms of performance.

First, we need to add two new dependencies. Once again, make sure to install the pinned versions:

$ npm install [email protected] [email protected] --save-dev

This will add two more dev dependencies to our package.json file. Our node_modules directory and package-lock.json file will also be updated automatically.

webpack Loaders

Next let's update our webpack.config.js file:

webpack.config.js
const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      }
    ]
  }
};

Here we configure our module further by adding specific rules. The test line tells webpack where to look for files that use the specified loaders. Note that the test line uses a regular expression to find files with a .css extension.

A loader preprocesses our code before it's actually loaded. We need these loaders because webpack only understands JavaScript, not other assets such as CSS. The loaders will actually transform our CSS into JavaScript code so webpack can bundle it.

Next, let's move our css directory into our src directory. After all, it's part of our source code, too. Finally, we need to import our css into our index.js file so it is available for webpack to bundle. To import it, we'll add the following import statement:

src/index.js
import './css/styles.css';

...

Finally, we can remove the following line from index.html:

<link rel="stylesheet" href="./../css/styles.css">

The <head> now looks like this:

dist/index.html
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script type="text/javascript" src="bundle.js"></script>
  <title>Shape Tracker</title>
</head>

It's time to $ npm run build. Now if we refresh the browser, we'll see our new CSS rule has been applied. No need for separate style tags in our HTML!

Lesson 13 of 43
Last updated October 18, 2021