[go: up one dir, main page]

0% found this document useful (0 votes)
72 views17 pages

A Mostly Complete Guide To Webpack 5 (2020)

A mostly complete guide to webpack 5 provides comprehensive instructions on how to use and configure webpack for modern JavaScript applications. It covers essential topics such as entry points, output, loaders, plugins, and code splitting, along with practical examples for setting up projects with React and SASS. The guide aims to help developers understand the underlying mechanisms of webpack while offering best practices for efficient configuration.

Uploaded by

er.manu27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
72 views17 pages

A Mostly Complete Guide To Webpack 5 (2020)

A mostly complete guide to webpack 5 provides comprehensive instructions on how to use and configure webpack for modern JavaScript applications. It covers essential topics such as entry points, output, loaders, plugins, and code splitting, along with practical examples for setting up projects with React and SASS. The guide aims to help developers understand the underlying mechanisms of webpack while offering best practices for efficient configuration.

Uploaded by

er.manu27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

5. Mode
6. Code splitting
VALENTINO GAGLIARDI / GET IN TOUCH
4. Getting started with webpack
5. First steps with webpack
Published: Jun 5, 2020 - Last updated: Dec 1, 2020 6. Configuring webpack
7. Working with HTML
A mostly complete guide to 8. webpack's development
dev server
webpack 5 (2020) 9. Working with webpack's loaders
10. Working with CSS
11. Order of webpack loaders matters!
12. Working with SASS
13. Working with modern JavaScript
14. How to set up React, webpack 5, and Babel from scratch
15. Working with JavaScript's modules in webpack
16. Production mode
17. Code splitting with webpack
1. Code splitting with optimization.splitChunks

Table of Contents 2. Code splitting with dynamic imports

1. Should you learn webpack? 18. Further topics

2. Disclaimer 19. Wrapping up - Resources

3. Terminology. What is webpack?


1. Entry point
Should you learn webpack?
2. Output Today CLI tools as create-react-app or Vue cli abstract away most of the
configuration, and provide sane defaults.
3. Loaders
4. Plugins
https://www.valentinog.com/blog/webpack/ 1/34 https://www.valentinog.com/blog/webpack/ 2/34
30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

Even then, understanding how things work under the hood is beneficial The ultimate goal of webpack is to unify all these different sources and
because sooner or later you'll need to make some adjustment to the module types in a way that's possible to import everything in your
defaults. JavaScript code, and finally produce a shippable output.

In this guide we'll see what webpack can do, and how to configure it to
suit your needs.
Entry point
Disclaimer An entry point for webpack is the starting point from which all the
dependencies of a frontend project are collected. In practice, it's a simple
My tutorials are free, no strings attached. This means I have no obligation JavaScript file.
to keep them constantly updated to the latest releases of the packages.
Keep also in mind, frontend tooling changes so fast that I can't keep These dependencies form a dependency graph.
up updating every single blog post as quickly as $jsTool introduces
breaking changes. But, I try to do my best. If something doesn't work for The default entry point for webpack (since version 4) is src/index.js,
you, drop me a polite email, and I'll try to fix the tutorial if I have time. and it's configurable. webpack can have multiple entry points.
Enjoy!

Terminology. What is webpack? Output


As a JavaScript dev
developer you should be familiar with the term module. The output is where the resulting JavaScript and static files are collected
You might have heard about AMD modules, UMD, Common JS, ES during the build process.
modules.
The default output folder for webpack (since version 4) is dist/,
webpack is a module bundler and has a broader definition of what a configurable as well.
module is, specifically, for webpack, modules are:
The resulting JavaScript files are part of the so called bundle.
Common JS modules
AMD modules
Loaders
CSS import
Images url Loaders are third-party extensions that help webpack deal with
various file extensions. For example there are loaders for CSS, for
ES modules
images, or for txt files.
That is, webpack is able to ingest dependencies from any of these
sources.
https://www.valentinog.com/blog/webpack/ 3/34 https://www.valentinog.com/blog/webpack/ 4/34
30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

The goal of a loader is to transform files (other than JavaScript) in


mkdir webpack-tutorial && cd $_
modules. Once the file becomes a module, webpack can use it as a
dependency in your project.
npm init -y

Once inside install webpack, webpack-cli, and the webpack-dev-


dev
Plugins server:
Plugins are third-party extensions that can alter how webpack
works. For example there are plugins for extracting HTML, CSS, or for npm i webpack webpack-cli webpack-dev-server
dev --save-dev
dev
setting up environment variables.
To run webpack easily from an NPM script, open up package.json and
configure a "dev"
dev script:
Mode
"scripts": {
webpack has two modes of operations: development
dev and production. "dev"
dev : "webpack --mode dev
development"
The main difference between them is that production mode },
automatically applies minification and other optimizations to your
JavaScript code. With this script we instruct webpack to work in dev
development mode,
convenient for working locally.

Code splitting First steps with webpack


Code splitting, or lazy loading is an optimization technique for avoiding To run webpack in dev
development mode:
larger bundles.

With code splitting, developers


dev can decide to load whole blocks of npm run dev
JavaScript only in response to some user interaction, like clicks or route
changes (or other conditions). You should see the following error.

A piece of code that's splitted becomes a chunk.


ERROR in Entry module not found: Error: Can't resolve '.

Getting started with webpack Here webpack is looking for the default entry point, src/index.js.
To start off with webpack create a new folder and move into it to initialize Create the folder, and inside the same folder create a simple JavaScript
an NPM project: file:
https://www.valentinog.com/blog/webpack/ 5/34 https://www.valentinog.com/blog/webpack/ 6/34
30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

output
mkdir src
loaders
echo 'console.log("Hello webpack!")' > src/index.js plugins
code splitting
Now run again npm run dev and you should see no more errors. The
result of this run is a new folder named dist/, with a JavaScript file in it For example, to change the entry point path we can do:
named main.js:

const path = require("path");


dist
└── main.js module.exports = {
entry: { index: path.resolve(__dirname, "source", "ind
This is your first webpack bundle, also called output. };

Configuring webpack Now webpack will look in source/index.js for the first file to load. To
change instead the output of our bundle we can do:
For simpler tasks webpack could work without a configuration, but you'll
hit the limit pretty soon. To configure webpack through a file create a
const path = require("path");
webpack.config.js in the project folder:

module.exports = {
touch webpack.config.js output: {
path: path.resolve(__dirname, "build")
Webpack is written in JavaScript, and runs on top on a headless JavaScript }
environment such as Node.js. In this file you'll need at least a };
module.exports, which is the Common JS export for Node.js:
With this configuration webpack will put the bundle in build instead of
module.exports = { dist. (To keep things simple we'll stick to the default in this guide).
//
}; Working with HTML
In webpack.config.js we can change how webpack behaves by adding A web application without an HTML page is almost useless. To work with
or altering: HTML in webpack we need to install a plugin, html-webpack-plugin:

entry point
https://www.valentinog.com/blog/webpack/ 7/34 https://www.valentinog.com/blog/webpack/ 8/34
30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

</body>
npm i html-webpack-plugin --save-dev
dev </html>

Once the plugin is installed we can configure it: In a second we'll run this "app" with webpack's dev
development server.

const HtmlWebpackPlugin = require("html-webpack-plugin") webpack's development


dev server
const path = require("path");
In the first section of this guide we installed webpack-dev-server
dev . If you
module.exports = { forgot to add it, install the package now:
plugins: [
new HtmlWebpackPlugin({
npm i webpack-dev-server
dev --save-dev
dev
template: path.resolve(__dirname, "src", "index.ht
})
webpack-dev-server
dev is a convenient package for dev
development. Once
]
configured, we can launch a local server to serve our files.
};
To configure webpack-dev-server
dev , open up package.json and add a
Here we say to webpack, load an HTML template from src/index.html. "start" script:

The ultimate goal of html-webpack-plugin is twofold:


"scripts": {
it loads our HTML files "dev"
dev : "webpack --mode dev
development",
"start": "webpack serve --open 'Firefox'",
it injects the bundle(s) in the same file
},
Before moving on create a simple HTML file in src/index.html:
With this script we can run the server easily. Now run:
<!DOCTYPE html>
<html lang="en"> npm start
<head>
<meta charset="UTF-8"> Your default browser should open. In the browser's console you should
<title>Webpack tutorial</title> also see a script tag, with our main JavaScript bundle injected:
</head>
<body>

https://www.valentinog.com/blog/webpack/ 9/34 https://www.valentinog.com/blog/webpack/ 10/34


30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

//
};

The relevant configuration starts with the module key. Inside this key we
configure each loaders group, or a single loader, inside rules.

For each file we want to treat as a module we configure an object with


a test key, and with use:

{
test: /\.filename$/,
use: ["loader-b", "loader-a"]
}

test tells webpack "hey, treat this filename as a module". use instead,
defines what loaders are applied to the file.

Working with webpack's loaders Working with CSS


Loaders are third-party extensions that help webpack deal with
To work with CSS in webpack we need to install at least two loaders.
various file extensions. For example there are loaders for CSS, for
images, or for txt files. Loaders here are necessary for helping webpack to understand how to
deal with .css files.
The anatomy of a webpack loader, configuration wise, is the following:
To test CSS in webpack create a simple stylesheet in src/style.css:
module.exports = {
module: { h1 {
rules: [ color: orange;
{ }
test: /\.filename$/,
use: ["loader-b", "loader-a"] Also, add an HTML element to our HTML template in src/index.html:
}
]
}, <!DOCTYPE html>
<html lang="en">
https://www.valentinog.com/blog/webpack/ 11/34 https://www.valentinog.com/blog/webpack/ 12/34
30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

<head> use: ["style-loader", "css-loader"]


<meta charset="UTF-8"> }
<title>Webpack tutorial</title> ]
</head> },
<body> plugins: [
<h1>Hello webpack!</h1> new HtmlWebpackPlugin({
</body> template: path.resolve(__dirname, "src", "index.ht
</html> })
]
Finally, load the CSS in src/index.js: };

The relevant configuration starts with the module key:


import "./style.css";
console.log("Hello webpack!");
const HtmlWebpackPlugin = require("html-webpack-plugin")
Before testing the page we need to install the loaders: const path = require("path");

css-loader for loading CSS files with import module.exports = {


style-loader for loading the stylesheet in the DOM module: {
rules: [
Install the loaders: {
test: /\.css$/,
use: ["style-loader", "css-loader"]
npm i css-loader style-loader --save-dev
dev
}
]
Then configure them in webpack.config.js:
},
//
const HtmlWebpackPlugin = require("html-webpack-plugin") };
const path = require("path");
Now if you run npm start you should see the stylesheet loaded in the
module.exports = { HTML's head:
module: {
rules: [
{
test: /\.css$/,

https://www.valentinog.com/blog/webpack/ 13/34 https://www.valentinog.com/blog/webpack/ 14/34


30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

},
//
};

Here "style-loader" appears before "css-loader". But style-loader is for


injecting the style in the page, not for loading the actual CSS file.

The following configuration instead is valid:

//

module.exports = {
module: {
rules: [
{
test: /\.css$/,
Once CSS loaders are in place you can extract CSS files with use: ["style-loader", "css-loader"]
MiniCssExtractPlugin. }
]

Order of webpack loaders matters! },


//
In webpack, the order in which loaders appear in the configuration is };
of high importance. The following configuration is invalid:
webpack loaders are loaded from right to left, (or think as of top to
bottom).
//

module.exports = {
Working with SASS
module: { To work with SASS in webpack we need to install at least the
rules: [ appropriate loaders.
{
test: /\.css$/, Loaders here are necessary for helping webpack to understand how to
use: ["css-loader", "style-loader"] deal with .scss files.
}
] To test SASS in webpack create a simple stylesheet in src/style.scss:
https://www.valentinog.com/blog/webpack/ 15/34 https://www.valentinog.com/blog/webpack/ 16/34
30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

sass-loader for loading SASS files with import


@import url("https://fonts.googleapis.com/css?family=Kar
css-loader for loading CSS files as modules
$font: "Karla", sans-serif; style-loader for loading the stylesheet in the DOM
$primary-color: #3e6f9e;
Install the loaders:
body {
font-family: $font;
npm i css-loader style-loader sass-loader sass --save-de
de
color: $primary-color;
}
Then configure them in webpack.config.js:

Also, add some more HTML elements to our HTML template in


src/index.html: const HtmlWebpackPlugin = require("html-webpack-plugin")
const path = require("path");

<!DOCTYPE html>
module.exports = {
<html lang="en"> module: {
<head>
rules: [
<meta charset="UTF-8"> {
<title>Webpack tutorial</title>
test: /\.scss$/,
</head>
use: ["style-loader", "css-loader", "sass-loader
<body> }
<h1>Hello webpack!</h1>
]
<p>Hello sass!</p> },
</body>
plugins: [
</html>
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "src", "index.ht
Finally, load the SASS file in src/index.js: })
]
import "./style.scss"; };
console.log("Hello webpack!");
Again, the relevant configuration starts with the module key:
Before testing the page we need to install the loaders (and the sass
package for Node.js): const HtmlWebpackPlugin = require("html-webpack-plugin")
const path = require("path");
https://www.valentinog.com/blog/webpack/ 17/34 https://www.valentinog.com/blog/webpack/ 18/34
30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

Once SASS and CSS loaders are in place you can extract CSS files with
module.exports = { MiniCssExtractPlugin.
module: {
rules: [ Working with modern JavaScript
{
test: /\.scss$/, webpack doesn't know on its own how to transform JavaScript code.
use: ["style-loader", "css-loader", "sass-loader This task is outsourced to a third-party loader, specifically babel-loader,
} with babel.
]
}, babel is a JavaScript compiler and "transpiler". Given modern JavaScript
// syntax as input, babel is able to transform it to compatible code that
}; can run in (almost) any browser.

Before moving forward we need to install a bunch of packages:


Notice the order in which loaders appear: first, sass-loader, then css-
loader, finally style-loader. babel core, the actual engine
Now if you run npm start you should see the stylesheet loaded in the babel preset env for compiling modern Javascript down to ES5
HTML's head: babel loader for webpack

Let's pull in the dependencies:

npm i @babel/core babel-loader @babel/preset-env --save-

Then configure babel by creating a new file, babel.config.json. Here


we configure babel to use preset-env:

{
"presets": [
"@babel/preset-env"
]
}

Finally, configure webpack to use the loader for transforming JavaScript


files (I left the SASS too loader for a bit more context):
https://www.valentinog.com/blog/webpack/ 19/34 https://www.valentinog.com/blog/webpack/ 20/34
30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

const HtmlWebpackPlugin = require("html-webpack-plugin") const [a, b] = fancyFunc();


const path = require("path");
Now run npm run dev to see the transformed code in dist. Open up
module.exports = { dist/main.js and search for "fancyFunc":
module: {
rules: [
{ cyFunc2[1];\n\n//# sourceURL=webpack:///./src/index.js?"
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader Without babel, the code wouldn't be transpiled:
},
{ \n\nconsole.log(\"Hello webpack!\");\n\nconst fancyFunc
test: /\.js$/,
exclude: /node_modules/, Note: webpack works totally fine even without babel. The transpiling
use: ["babel-loader"] process is only necessary for shipping ES5.
}

},
]
How to set up React, webpack 5, and
plugins: [ Babel from scratch
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "src", "index.ht To use React components with webpack, alongside with babel loader you
}) should also install the babel preset for React:
]
}; npm i @babel/core babel-loader @babel/preset-env @babel/

To test the transformation, write some modern syntax in src/index.js: Once done, configure babel to use the React preset in
babel.config.json:
import "./style.scss";
console.log("Hello webpack!"); {
"presets": ["@babel/preset-env", "@babel/preset-react"
const fancyFunc = () => { }
return [1, 2];
}; At this point you can install React with:

https://www.valentinog.com/blog/webpack/ 21/34 https://www.valentinog.com/blog/webpack/ 22/34


30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

webpack makes a joy working with ES modules and modularized


npm i react react-dom
code.

Finally, you can write your components in the project. To test things out To try out ES modules in webpack let's create a module in a new file at
you can create a component in src/index.js: src/common/usersAPI.js with the following code:

import React, { useState } from "react"; const ENDPOINT = "https://jsonplaceholder.typicode.com/u


import { render } from "react-dom";
export function getUsers() {
function App() { return fetch(ENDPOINT)
const [state, setState] = useState("CLICK ME"); .then(response => {
if (!response.ok) throw Error(response.statusText)
return <button onClick={() => setState("CLICKED")}>{ return response.json();
} })
.then(json => json);
render(<App />, document.getElementById("root")); }

Now when running webpack's dev server with npm start you should Now in src/index.js you can load the module and use the function:
see the component in the browser. (Don't forget to add a <div> in the
page with the relevant id).
import { getUsers } from "./common/usersAPI";
import "./style.scss";
Working with JavaScript's modules in console.log("Hello webpack!");
webpack
getUsers().then(json => console.log(json));
webpack treats a whole range of files as modules. But, let's not forget its
main purpose: loading ES modules. For a refresher on ES modules: All I need to know about ECMAScript
modules.
Up until 2015 JavaScript didn't have a standard mechanism for code
reuse. There had been a lot of attempts to standardize this aspect, which
resulted in a messy fragmentation during the years.
Production mode
As introduced earlier, webpack has two modes of operation:
You might have heard about AMD modules, UMD, or Common JS. There
dev
development and production. So far we worked only in dev
development
was no clear winner. Finally, with ECMAScript 2015, ES modules landed in
mode.
the language. We now have an "official" module system.
https://www.valentinog.com/blog/webpack/ 23/34 https://www.valentinog.com/blog/webpack/ 24/34
30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

In development
dev mode, webpack takes all the JavaScript code we write, There is a limit that the webpack community considers the maximum size
almost pristine, and loads it in the browser. for the initial bundle of an application: 200KB. To understand why
keeping bundles small is paramount, search for "The Cost of JavaScript"
No minification is applied. This makes reloading the application in on Google.
development faster.
dev
There are three main ways to activate code splitting in webpack:
In production mode instead, webpack applies a number of
optimizations: with multiple entry points

minification with TerserWebpackPlugin to reduce the bundle size with optimization.splitChunks

scope hoisting with ModuleConcatenationPlugin with dynamic imports

It also set process.env.NODE_ENV to "production". This environment The first technique based on multiple entry points works well for smaller
variable is useful for doing things conditionally in production or in projects, but it's not scalable in the long run. Here we'll focus only on
optimization.splitChunks and dynamic imports.
dev
development.

To configure webpack in production mode, open up package.json and


add a "build" script: Code splitting with optimization.splitChunks
Consider a JavaScript application using Moment.js, the popular JS library
"scripts": {
for times and dates. There are better alternatives to it, but for a moment
"dev"
dev : "webpack --mode dev
development",
(no pun intended) let's prove my point.
"start": "webpack serve --open 'Firefox'",
"build": "webpack --mode production" Install the library in your project folder:
},

Now when running npm run build webpack will produce a minified npm i moment
bundle.
Now wipe out the content of src/index.js and import the library
Code splitting with webpack there:

Code splitting refers to an optimization technique aiming at: import moment from "moment";

avoid big bundles Run a build with npm run build and look at the output:
avoid dependencies duplication

https://www.valentinog.com/blog/webpack/ 25/34 https://www.valentinog.com/blog/webpack/ 26/34


30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

main.js 350 KiB 0 [emitted] [big] main


Code splitting with dynamic imports
A more powerful technique for code splitting uses dynamic imports to
The whole library is bundled in the main entry point of our app. Not load code conditionally. webpack offered dynamic imports long before
good. With optimization.splitChunks we can move out moment.js this feature shipped in ECMAScript 2020.
from the main bundle.
This approach is widely used in modern frontend library like Vue and
To configure code splitting open up webpack.config.js and add the React (React has its own way, but the concept is the same).
optimization key to your configuration, configured as follows:
Code splitting might be used:
const HtmlWebpackPlugin = require("html-webpack-plugin")
at the module level
const path = require("path");
at the route level
module.exports = {
For example, you can load conditionally some JavaScript module in
module: {
response to a user interaction, like a click, or a mouse move. Or, you can
// omitted for brevity
load relevant portions of your code on response to route changes.
},
optimization: { To get started with dynamic imports, wipe out the content of
splitChunks: { chunks: "all" }
src/index.html, and place in the following HTML instead:
},
// omitted for brevity
}; <!DOCTYPE html>
<html lang="en">
Run a build with npm run build and look at the output: <head>
<meta charset="UTF-8">
<title>Dynamic imports</title>
main.js 5.05 KiB 0 [emitted] ma </head>
vendors~main.js 346 KiB 1 [emitted] [big] ve <body>
<button id="btn">Load!</button>
We now have a vendors~main.js with moment.js, while the main entry </body>
point has a more reasonable size. </html>

Note: even with code splitting moment.js remains a gigantic library.


Make sure to still have the fetch module in src/common/usersAPI.js:
There are better alternatives like luxon or date-fns.

https://www.valentinog.com/blog/webpack/ 27/34 https://www.valentinog.com/blog/webpack/ 28/34


30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

getUsers().then(json => console.log(json));


const ENDPOINT = "https://jsonplaceholder.typicode.com/u });

export function getUsers() { The problem is that ES modules are static, meaning we cannot change
return fetch(ENDPOINT) imports at runtime.
.then(response => {
if (!response.ok) throw Error(response.statusText) With a dynamic import instead we can choose when to load our code:
return response.json();
})
const getUserModule = () => import("./common/usersAPI");
.then(json => json);
}
const btn = document.getElementById("btn");

Now in src/index.js create the following logic:


btn.addEventListener
dEv ("click", () => {
getUserModule().then(({ getUsers }) => {
const btn = document.getElementById("btn"); getUsers().then(json => console.log(json));
});
btn.addEventListener
dEv ("click", () => { });
//
}); Here we create a function to load the module dynamically:

Nothing happens if you run npm run start to see and click the button
const getUserModule = () => import("./common/usersAPI");
in the interface.

Now imagine we want to load a list of users after someone clicks the Then in the event listener we chain then() to the dynamic import:
button. A "naive" approach can use a static import to load the function
from src/common/usersAPI.js: btn.addEventListener
dEv ("click", () => {
getUserModule().then(/**/);
import { getUsers } from "./common/usersAPI"; });

const btn = document.getElementById("btn"); This gives the ability to extract our getUsers function with object
destructuring:
btn.addEventListener
dEv ("click", () => {
btn.addEventListener
dEv ("click", () => {
getUserModule().then(({ getUsers }) => {
https://www.valentinog.com/blog/webpack/ 29/34 https://www.valentinog.com/blog/webpack/ 30/34
30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

//
});
});

Finally, we use our function as usual:

//

btn.addEventListener
dEv ("click", () => {
getUserModule().then(({ getUsers }) => {
getUsers().then(json => console.log(json));
});
});

When you now load the page for the first time with npm run start you
see the main bundle loaded in the console:
The lazy "chunk" is 0.js.

By prefixing the import path with /* webpackChunkName:


"name_here" */ we can also control the chunk name:

const getUserModule = () =>


import(/* webpackChunkName: "usersAPI" */ "./common/us

const btn = document.getElementById("btn");

btn.addEventListener
dEv ("click", () => {
getUserModule().then(({ getUsers }) => {
getUsers().then(json => console.log(json));
});
});

The chunk now will have the desired name:


Now "./common/usersAPI" loads only when clicking the button:
https://www.valentinog.com/blog/webpack/ 31/34 https://www.valentinog.com/blog/webpack/ 32/34
30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020) 30/04/2025, 12:22 A mostly complete guide to webpack 5 (2020)

Thanks for reading!

Hi! I'm Valentino! I'm a freelance consultant with a wealth of


experience in the IT industry. I spent the last years as a
frontend consultant, providing advice and help, coaching and

Further topics
training on JavaScript, testing, and software development.
dev Let's
get in touch!

Other interesting worth going through are:

prefetching and preloading, which work wonderfully with dynamic

🦄 🦄
imports
Valentino Gagliardi
caching
is part of
Wrapping up - Resources The Great Django Webring
[Prev] [Random] [Next]
In this post we covered webpack's fundamentals: code splitting,
configuration, loaders, plugins. Of course there's a lot more.
:: All rights reserved 2025, Valentino Gagliardi - Privacy policy - Cookie policy ::
Once reading this introductory guide, check out these great resources:

webpack documentation
Survive JS - webpack

https://www.valentinog.com/blog/webpack/ 33/34 https://www.valentinog.com/blog/webpack/ 34/34

You might also like