3.2 React Tooling

Webpack

# What is Webpack?

Webpack is a comprehensive Node.js based development tool that replaces older "task runners" like grunt or gulp and integrates other tools like Sass, Babel, PostCSS and more.

Webpack allows us to author our code in smaller organized modules, and then package them up into efficient compact bundles for delivery to the browser.

# Why do we need it?

  • Provides a development web server with hot-module-reloading (opens new window)
  • Orchestrate multiple build tools
  • Automate dependency management
  • Generate smaller asset files to be loaded by the browser

# Practice Exercises

Fork this starter repo (opens new window), and then clone your forked version to your laptop.

Then cd into your new project and initialize it with npm.

npm init --yes
1

Add Webpack as a development dependency

npm install webpack webpack-cli --save-dev
1

# Run Webpack with default config

One of the strengths of Webpack is that it is highly configurable and can utilize many third-party plugins to extend its capabilities. However, starting with Webpack version 4, you can now run it without any special configuration settings to easily get started.

npx webpack
1

You should now see a new compiled and minified version of your source code in one combined file called dist/main.js

# With a configuration file

The default behaviour is equivalent to placing this webpack.config.js file in the root of your project.

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
};
1
2
3
4
5
6
7
8
9

# Bundle CSS with the JavaScript modules that need it

The Webpack module loaders can handle more than just JavaScript.

This enables you to import ./style.css into the file that depends on that styling. Now, when that module is run, a <style> tag with the stringified css will be inserted into the <head> of your html file.

Lets try it out. In the src folder, create a new style.css file and use the import syntax to include it in your index.js module.

li {
  font-size: 1.5rem;
}
1
2
3
import './style.css';
1

Running webpack now will generate an error, because we have not told it how to handle CSS modules. Install the style-loader and the css-loader modules from NPM.

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

Now update the webpack.config.js file to look like this ...









 
 
 
 
 
 
 
 
 

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

Now run npx webpack again. Reload the index.html file in the browser and you should see the styling applied.

This is just scratching the surface of what Webpack can do. Please spend some time reading the docs and tutorials below to learn more.

# PostCSS

PostCSS (opens new window) is a JavaScript based tool for optimizing your CSS. It supports a wide range of plugins that solve the most common issues. e.g.

  • Autoprefixer
  • Preset_Env
  • CSS Modules
  • stylelint
  • cssnano
  • + hundreds more

# Add to Webpack config

You will need to add the postcss-loader and postcss NPM modules to your project.

npm install --save-dev postcss-loader postcss
1

You will also need to install any PostCSS plugins that you need. For this example, lets use postcss-preset-env to add backwards compatible polyfills and vendor prefixes based on the browserlist setting in package.json.

npm install --save-dev postcss-preset-env
1

Then you will need to add postcss-loader to the use array for CSS files in webpack.config.js. Don't forget to import the plugin module at the top.


 













 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 






const path = require('path');
const postcssPresetEnv = require('postcss-preset-env');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          { loader: 'css-loader', options: { importLoaders: 1 } },
          {
            ident: 'postcss',
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: [
                  postcssPresetEnv({
                    stage: 2,
                    features: {
                      'nesting-rules': true,
                    },
                  }),
                ],
              },
            },
          },
        ],
      },
    ],
  },
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

And, so that we can see it do something, update your style.css file to look like this:

.app {
  & li {
    color: gray(50);
    font-size: 1.5rem;
  }
}
1
2
3
4
5
6

Lets test it!

Run npx webpack again and refresh the browser.

# Reference Resources

Last Updated: : 9/4/2021, 6:05:05 PM