Introduction
In the previous lesson, we introduced ES6 modules (ESM) and npm. The introduction of ESM greatly mitigated some of the issues with managing individual script files and dependencies. However, downloading a large number of module files individually can reduce performance, especially as more third party files are imported.
Fortunately, more recent web technologies have greatly improved these aspects, but bundlers still provide us with a lot of power to process and optimize our code in various ways. This power, however, does come with the small cost of needing to configure a bundler. For now, our needs are few and simple, and we can look at the basic things one at a time.
Awareness of bundlers and basic experience with them is valuable. While in recent years, new build tools have come out that handle a lot of basic configuration for us, in the real world, you may not always get a chance to use these shiny new tools. It’s very reasonable to end up working with codebases that use tools that require more manual configuration. Even when you work with tools that handle more things for you, it’s useful to understand what those tools are actually doing for you.
Ensure you are running the latest LTS version of Node.js before proceeding. If necessary, you can use NVM to install the latest LTS version as per the Installing Node.js lesson.
Lesson overview
This section contains a general overview of topics that you will learn in this lesson.
- The purpose of bundlers and how they work.
- Bundling with Webpack.
- Webpack’s development server.
Bundling
In the ES6 modules lesson, we learned what an entry point is, what a dependency graph is, and how to add an entry point file to HTML as a module script. With bundling, the same concepts of entry points and dependency graphs apply: we provide the bundler with an entry point. It then builds a dependency graph from that file, combines all relevant files together, and then outputs a single file with all the necessary code included.
While it does this, we could also get it to do a whole bunch of other things, such as minifying our code, image optimizations, or even “tree shaking”. Most of these extra optimizations are out of the scope of this course; we will instead be focusing on basic bundling of JavaScript, and handling HTML, CSS, and images.
Webpack
Webpack is one of the most popular JavaScript bundlers, if not the most popular one, and has been for a long time. Let’s get started with bundling!
We’ll first need to make a new directory for our practice app, then create a package.json file in it for npm to record information about packages we use (like Webpack). Run the following in your terminal:
mkdir webpack-practice &&
cd webpack-practice &&
npm init -y --init-type=module
This should create a package.json file inside the webpack-practice directory you just made and entered. Now we can install Webpack:
npm install --save-dev webpack webpack-cli
npm audit vulnerabilities
After installing a package with npm, the output may mention something about some vulnerabilities and running npm audit fix. Even though these are technically vulnerabilities, they are very likely to be extremely specific niche things and as far as TOP is concerned, highly unlikely to be of any actual danger to anything you do in the curriculum, so you can ignore these if you see them.
These are more relevant if you’re making production apps with higher stakes, where you’d need to examine the vulnerabilities themselves to see if they can tangibly hurt you.
Note that we included the --save-dev flag (you can also use -D as a shortcut), which tells npm to record our two packages as development dependencies. We will only be using Webpack during development. The actual code that makes Webpack run will not be part of the code that the browser will run.
Also notice that when these finished installing, npm created a node_modules directory and a package-lock.json file for us. node_modules is where Webpack’s actual code (and a whole bunch of other stuff) lives, and package-lock.json is just another file npm uses to track more specific package information.
src and dist
When dealing with Webpack (and often with any other bundler or build tool), we have two very important directories: src (short for “source”) and dist (short for “distribution”). We could technically call these directories whatever we want, but these names are conventions.
src is where we keep all of our website’s source code, essentially where all of our work will be done (with an exception being altering any configuration files in the root of the project). When we run Webpack to bundle our code, it will output the bundled files into the dist directory. The idea is that if someone were to fork or clone the project, they would not need the dist directory, as they’d just be able to run Webpack to build from src into their own dist. Similarly, to deploy our website, we would only need the dist code and nothing else. Keep that in mind! Work inside src, build into dist, then deploy from there!
Bundling JavaScript
Import file extensions
Normally, with ESM, we need to specify file extensions when we import from other files (e.g. "./greeting.js"). With Webpack and many other bundlers, some file extensions like .js are optional, as Webpack will automatically check extensionless file paths for .js files by default (e.g. "./greeting").
This is a feature of Webpack, not ESM.
In this lesson, examples with imports will always include the file extension where appropriate to be explicit.
Now that we’ve installed Webpack in our project directory, let’s create a src directory with two JavaScript files inside it: index.js and greeting.js.
mkdir src && touch src/index.js src/greeting.js
Inside our two JavaScript files, we’ll have the following:
// index.js
import { greeting } from "./greeting.js";
console.log(greeting);
// greeting.js
export const greeting = "Hello, Odinite!";
Great, now we have an index.js that imports from, and so depends on, greeting.js. In order to bundle this, we’ll also want a Webpack configuration file, which will contain all the details we need for bundling, such as the entry point, the output destination, and any other extra setup.
Back in your project root (so outside of src), create a webpack.config.js file that contains the following:
// webpack.config.js
import path from "node:path";
export default {
mode: "development",
entry: "./src/index.js",
output: {
path: path.resolve(import.meta.dirname, "dist"),
clean: true,
},
};
You’ll notice the exported object contains a few key sections:
mode: For now, we will just leave this in development mode, as it will be more useful to us. We will revisit this and production mode in a later lesson.entry: A relative file path from the config file to whichever file is our entry point, which in this case issrc/index.js.output: An object containing information about the output bundle.path: An absolute path to the output directory, in this case,dist. If this directory doesn’t already exist when we run Webpack, it will automatically create it for us as well. Don’t worry too much about why we have thepath.resolvepart - it’s just to ensure we get a proper absolute path regardless of environment.clean: If we include this option and set it totrue, then each time we run Webpack to bundle, it will empty the output directory first before bundling the files into it. This helps us keepdistclean, so it only contains the files produced by the most recent bundling.
With these files all in place, let’s run Webpack and see what happens!
npx webpack
You should see that Webpack has created a dist directory for us containing a main.js file! It’s combined both of our modules into a single file. Inside this file is…a lot of stuff… Don’t worry, most of this stuff is just for development tools we will use later. If you go ahead and run this file with node dist/main.js, you should see Hello, Odinite! logged in the terminal.
Congratulations! You’ve just made your first bundle with Webpack!
Handling HTML
Let’s actually include some HTML. After all, we’re interested in making websites! In the past, bundlers only handled JavaScript by default but could be configured with things like plugins to handle non-JavaScript, such as HTML, CSS, images etc. Nowadays however, many bundlers handle these things automatically, and Webpack is no exception.
Let’s make an index.html in our src directory. Put in the usual HTML boilerplate and add our index.js as an entry point in a module script.
<!-- src/index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script type="module" src="./index.js"></script>
<title>Document</title>
</head>
<body></body>
</html>
The only things left are to change our bundling entry point from src/index.js to src/index.html and tell Webpack to expect to handle a module script:
// webpack.config.js
import path from "node:path";
export default {
mode: "development",
entry: "./src/index.html",
output: {
module: true,
path: path.resolve(import.meta.dirname, "dist"),
clean: true,
},
};
Now that Webpack knows to start with our HTML file, run npx webpack then check inside the dist directory. Now we have both a dist/index.html and dist/index.js. Webpack read our HTML file, found our JavaScript entry point, bundled the JavaScript into a single file, and put the result in the dist directory. Open dist/index.htnl in Live Preview and you should see our greeting in the devtools console.
Let’s see how we’d handle CSS.
Loading CSS
Webpack can also handle CSS by default. There are several ways you can link CSS to your site, but we’ll introduce a way that’s quite commonly seen in the wild, and will be extra relevant later in the curriculum when working with other tools.
Normally, you wouldn’t be able to import CSS in your JavaScript modules, not without some finicky stuff. Bundlers like Webpack can recognise various non-JavaScript file types and bundle them accordingly, including CSS. For example, let’s create a styles.css file in our src directory:
/* src/styles.css */
body {
background-color: rebeccapurple;
}
You can now import your CSS file into one of your JavaScript files. src/index.js makes sense. We don’t need anything from the imported CSS file itself, so we can just use a side effect import:
// src/index.js
import "./styles.css";
import { greeting } from "./greeting.js";
console.log(greeting);
Once again, bundle with Webpack using npx webpack, then open dist/index.html in Live Preview and enjoy the beautiful purple screen!
What about link tags?
You could 100% just use a <link rel="stylesheet"> element in your HTML file as usual. In the real world, however, projects often contain many moving parts and many modules. Eventually, it becomes easier to work with multiple smaller CSS files that you import in the modules where they’re needed. There are even ways those files can be scoped only to those modules and not globally!
We’re only introducing the minimum to allow you to import your CSS into your JavaScript, but many build tools and more sophisticated bundler configurations will do a lot more to imported CSS than what we’re showing here. We just want to expose you to the idea and syntax for now.
Loading images
If we have any local image files we want to include within our website, they will require a little extra configuration.
Image files used in our HTML (e.g. src for an <img> element) and CSS inside url() functions are automatically handled by Webpack, but what if we need to use a local image file in our JavaScript (such as when manipulating the DOM to create or edit img elements and set their src attribute)? In this case, we need to import the images into our JavaScript module. We’ll need to tell Webpack that these kinds of files will be assets so it can handle them accordingly:
// webpack.config.js
import path from "node:path";
export default {
mode: "development",
entry: "./src/index.html",
output: {
module: true,
path: path.resolve(import.meta.dirname, "dist"),
clean: true,
},
module: {
rules: [
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: "asset/resource",
},
],
},
};
Seems fancy, but going by Webpack docs, setting this rule tells Webpack that if it encounters an imported module (of type PNG/SVG/JPG/JPEG/GIF) then it should treat it as an asset. What this means for Webpack is that it’ll default export a file path to that file from that module import. You can always edit the regex in the test property to remove any file extensions you don’t need or add any extensions you do need. What’s shown above is straight from Webpack’s Asset Management guide and will recognize most of the common image file extensions.
Then, in whatever JavaScript module we want to use that image in, we just have to default import it.
// src/index.js
import odinImage from "./odin.png";
const image = document.createElement("img");
image.src = odinImage;
document.body.appendChild(image);
The reason we have to import it is so that the odinImage variable contains the correct file path, even when we bundle into dist. If we just wrote image.src = "./odin.png";, then the “file path” would just be a plain string. When we bundle into dist, Webpack will not magically recognize that this string in our JavaScript references a file and so will not include it in the bundle. When deploying what’s in dist, the image file won’t be there! Even if we put it there, the bundle structure may not match our path, so we can’t naively hard-code it. This isn’t an issue with image paths in HTML or CSS, because those situations aren’t ambiguous (e.g. using url() or a <img> element’s src). Normal JavaScript strings could be anything, however, not necessarily a file path.
When we import it and set the correct asset/resource rule, Webpack will recognize the import, include the image file when we bundle, and also make sure the imported variable contains the correct file path at the end.
You might also notice that when images are included when bundling, the output image file in dist has a different file name (it will likely be some jumble of numbers and letters). By default, Webpack gives your bundled image files a new name by hashing their contents. You do not need to know how this works, nor do you need to dig into the details of why, nor how to change it. You just need to be aware that this is expected behavior (it’s to do with preventing issues with the browser cache and matching file names).
You only need to configure what you need
In this lesson, we’re just introducing you to some basics of bundlers to get you making sites. In the future, you may end up working with things that have more sophisticated configurations, maybe with third-party loaders or plugins etc., for things such as custom fonts or preprocessors. You can always use Google or reference Webpack’s documentation (or whatever bundler’s documentation) for instructions on what you’d need when that time comes.
Webpack dev server
During this lesson, did you get a bit annoyed with having to run npx webpack to rebundle with every change? Fortunately, there are multiple solutions for this, and we will focus on what we think is the most useful option: webpack-dev-server. Install it as follows:
npm install --save-dev webpack-dev-server
You’ve been using Live Preview so far. However, Live Preview is just a generic lightweight dev server meant for simple little things without much setup. Now that we have a bundler in the mix, a purpose-built dev server makes a lot more sense. With webpack-dev-server, we won’t have to keep running npx webpack after each change we make.
It works by bundling your code behind the scenes (as if we ran npx webpack, but without saving the files to dist), and it does this every time you save a file that’s used in the bundle. We can also use something called a source map so that any error messages reference files and lines from our development code and not the jumbled mess inside our single bundled .js file! Being purpose-built for Webpack, it integrates well with it and is highly configurable too (though we won’t need much for our purposes).
Once installed, in our webpack.config.js, we only need to add a couple more properties somewhere in the configuration object (the order of these properties does not matter):
// webpack.config.js
import path from "node:path";
export default {
mode: "development",
entry: "./src/index.html",
output: {
module: true,
path: path.resolve(import.meta.dirname, "dist"),
clean: true,
},
devtool: "eval-source-map",
devServer: {
watchFiles: ["./src/index.html"],
},
module: {
rules: [
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: "asset/resource",
},
],
},
};
Firstly, we add a source map by setting eval-source-map as a devtool option. If we don’t do this, any error messages we get won’t necessarily match up to the correct files and line numbers from our development code. In the devtools “Sources” tab, we also won’t be able to find our original untouched code, making the Chrome debugger harder to use. Adding this source map will solve both of these problems for us.
Secondly, we make sure webpack-dev-server is watching our HTML file so all our src changes will automatically refresh the site.
Once set up, we can start up the dev server using the following command:
npx webpack serve
Our site will then be available via http://localhost:8080/ by default.
Restart the dev server upon config changes
Note that the webpack-dev-server only reads your webpack configuration when you start it. If you change the webpack config file while the dev server is running, it will not reflect those config changes. Use Ctrl + C in the terminal to kill it then rerun npx webpack serve to apply the new config.
Rounding up
This all might seem like a lot. You’ve gone from just having some basic HTML, CSS and JS files, and not needing much else to suddenly needing configuration file and third-party libraries, fancy structures etc. In the real world, as apps get more complex, we need tools that can improve our development experience while optimizing things in production. Even though we’re not using all of the features available to us right now, a general understanding of what these sorts of tools are doing for us is valuable. Later in the curriculum, you will use different tools that abstract a lot of these underlying mechanisms away from us. Using them and having no clue what they’re actually doing for you can make things harder for you when you eventually encounter a situation that actually needs some kind of manual configuration.
In a later lesson, we will introduce some extra things that can make setting up and working with Webpack much quicker and more straightforward. For now, however, it’s good to get a little manual practice in.
Assignment
- Start by reading the Webpack concepts page to get a general understanding of some of the main terms.
- Webpack’s Asset Management guide goes through some examples of how to handle various kinds of assets, like CSS, images, and fonts. You’ll see that its examples use
npm run buildto bundle the files; in these examples, that’s the equivalent ofnpx webpack. We will go through npm scripts in a later lesson.