Webpack

by Gisle Hannemyr

This chapter starts out with a classic “Hello world”-tutorial to introduce webpack. This tutorial will also describe how to install webpack locally. It then proceeds to discuss its sass-loader plugin and how to use webpack to compile SASS to CSS.

Table of contents

Introduction

Webpack is a static module bundler that is part of the Node.js ecosystem. It is made primarily for JavaScript, but it can transform front-end assets such as HTML, CSS, SASS and images if the corresponding loaders are included. Once installed, you can interact with webpack either using the CLI or an API. It is licensed under the ISC license.

Installation and “Hello world”-tutorial

To introduce webpack, we shall set up webpack in a local directory and use it to create an application that will use Javascript to display “Hello world” in the browser. It is not recommended to install webpack globally.

First create a directory named “webpack-demo”, initialize npm, install webpack, and install the webpack-cli (CLI tool):

$ mkdir webpack-demo
$ cd webpack-demo
$ npm init -y
$ npm install --save-dev webpack webpack-cli
$ npx webpack -v
webpack 5.37.0
webpack-cli 4.7.0

This will create a file named “package.json” and directory named “node_modules”, that will hold all node modules av that our local development environment shall need, including webpack and webpack-cli.

tipWhen installing a package that will be bundled into your production bundle, you should use npm install --save. If you're installing a package for development purposes (e.g. a linter, testing libraries, etc.) then you should use npm install --save-dev.

You also should edit the generated package.json as indicated below:

  "description": "",
- "main": "index.js",
+ "private": true,

This marks our package as private, to prevent it being published accidentally.

Next, set up the directory structure to work with webpack:

$ mkdir dist
$ touch dist/index.html
$ mkdir src
$ touch src/index.js

This separates the source code (/src) from the distribution code (/dist). The source code is the code that we'll write and edit. The distribution code is the minimized and optimized output of our build process that will eventually be loaded in the browser.

Create dist/index.html with the following content:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Hello world</title>
  </head>
  <body>
    <script src="main.js"></script>
  </body>
</html>

The content of main.js will be generated later, using webpack.

technical Even though it is now placed in the /dist directory, index.html is created manually. It is, however. possible to generate index.html. Once this is done, it should be safe to empty the dist directory and to regenerate all the files within it.

The content of src/index.js:

import _ from 'lodash';

function component() {
  const element = document.createElement('div');

  element.innerHTML = _.join(['Hello', 'world'], ' ');

  return element;
}

document.body.appendChild(component());

The global variable “_” is used in this script. It comes from Lodash, so it is imported from that library.

technicalThe Lodash (Wikipedia) Javascript library provides utility functions for common programming tasks using the functional programming paradigm.

To bundle the Lodash dependency with index.js, install the library locally:

$ npm install --save lodash

We are now ready to run webpack, using npx (the Node.js package runner). Basically, it will read our script (src/index.js, and generate dist/main.js as the output:

$ npx webpack --mode=production
asset main.js 69.5 KiB [emitted] [minimized] (name: main) 1 related asset
runtime modules 1010 bytes 5 modules
cacheable modules 532 KiB
  ./src/index.js 215 bytes [built] [code generated]
  ./node_modules/lodash/lodash.js 531 KiB [built] [code generated]

You may now copy the contents of the /dist directory to the webroot of your website. You should see a mostly blank page with the words: “Hello world”.

If you want to mode configuration option in a configuration file, please see the following pages on webpack.js.org: Configuration and Mode.

TL;DR: This should be the contents of webpack.config.js:

module.exports = {
  mode: 'production',
};

Source: webpack.js.org - Getting Started.

Add support for SASS to Webpack

We are going to use the following plugins:

$ npm install --save-dev sass-loader style-loader css-loader
$ npm install --save-dev mini-css-extract-plugin sass

Create a file named style.scss with the following content:

$body-color: red;
body {
  color: $body-color;
}

Inport it in src/index.js by adding the folowing line at the top:

import "./style.scss";

Modify webpack.congig.js. It should now have the following content:

module.exports = {
  mode: 'production',
  module: {
    rules: [
      {
        test: /\.s[ac]ss$/i,
        use: [
          // Creates 'style' nodes from JS strings
          "style-loader",
          // Translates CSS into CommonJS
          "css-loader",
          // Compiles Sass to CSS
          "sass-loader",
        ],
      },
    ],
  },
};  

Run webpack:

$ npx webpack

This will bundle the generated CSS with the Javascript in the file dist/main.js.

Extract to separate CSS-files

To compile an SCSS file with Webpack, and extraxt it into its own CSS file is not trivial.

There are two possibilities to extract a style sheet from the bundle:

We are going to use the first of these, and also Dart sass. The following plugins will be used, in addition to those already installed:

$ npm install --save-dev mini-css-extract-plugin sass
z

Source: webpack.js.org - sass-loader

- crash course
- handbook
- faster
- florian

Final word


Last update: 2021-05-17 [gh].