Deep dive into webpack and what problems it can solve for you
Posted
Updated
Europe’s developer-focused job platform
Let companies apply to you
Developer-focused, salary and tech stack upfront.
Just one profile, no job applications!
This article is based on Node v18.13.0 and webpack v5.8.2
In a nutshell, webpack is a static module bundler for modern JavaScript applications. When it processes the application, it builds a dependency graph and then combines every module your project needs into bundles, which are static assets to serve your content from.
💰 The Pragmatic Programmer: journey to mastery. 💰 One of the best books in software development, sold over 200,000 times.
"Okay, but why do we need it and what are the benefits?", you might be asking. Let's dive a bit deeper, and answer your questions.
If you are around long enough in web development, you have noticed that websites are not written in plain HTMl with a bit of JavaScript anymore, they're often entirely built by JavaScript (or TypeScript), and often use SSR (Server Side Rendering). In that case, we have to bundle, minify, and transpile the code into something browsers can understand, and this spot is where webpack comes in.
Webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it internally builds a dependency graph from one or more entry points and then combines every module your project needs into one or more bundles, which are static assets to serve your content from.
This bundling allows you to write the latest JavaScript with Babel or use TypeScript, and compile it into something cross-browser compatible minified. Webpack also allows you to import static assets into your JavaScript.
In a development environment, webpack supplies you with a development server that can update modules and
styles instantly when you save (hot reloading). For example vue create
and create-react-app
use webpack under the hood.
Webpack can do much more than that, let's start with the basics to get familiar with the concepts. Have a look at the core concepts of webpack at the webpack docs.
Let's start with the basic setup of a mini project to practically illustrate why webpack is an essential tool. This sample is sourced from webpack.
Create a webpack-demo folder and initialize npm and install webpack and the webpack-cli as devDependencies.
mkdir webpack-demo
cd webpack-demo
npm init -y
npm install webpack webpack-cli --save-dev
Now we'll create an index.html
file, a src
folder, and add an index.js
file.
touch index.html
mkdir src
cd src
touch index.js
Add this sample code to your index.js
file:
function component() {
const element = document.createElement('div');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
Add this code to your index.html
file.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Getting Started</title>
<script src="https://unpkg.com/[email protected]"></script>
</head>
<body>
<script src="./src/index.js"></script>
</body>
</html>
We also need to adjust our package.json
file to mark our package as private and to remote the main entry.
This is to prevent an accidental publish of your code.
The package.json should look like this:
{
"name": "webpack-demo",
"version": "1.0.0",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"webpack": "^5.88.2",
"webpack-cli": "^5.1.4"
}
}
Now open the index.html
in your browser, you should see hello webpack
.
In this example, there are implicit dependencies between the <script>
tags.
This means, that the index.js
file depends on lodash
being included before it runs.
This is because index.js never explicitly declared a need for lodash; it assumes that the global variable _
exists.
This approach can lead to serious problems:
Don't worry. There is a solution to all these problems. Webpack can manage this instead, and create a bundle.
To create a bundle (in this example), we first have to separate our source code from the distribution code.
We create a dist
folder, and move the index.html
into this folder. (Please be aware,
in a normal setup the index.html is created via webpack. This is only a quick showcase.)
The source code is the code that we'll write and edit, and the distribution code is the minimized and optimized output of our build process that will be loaded in the browser.
Create a dist folder and move the index.html into it.
mkdir dist
mv index.html dist/ # to move the index.html file into dist
To bundle the lodash
dependency with index.js
, we'll need to install the library locally:
npm install lodash
After installing it, lodash has to be imported. Add the following code to index.js
:
import _ from 'lodash';
Since we are going to be bundling our scripts, we have to update our index.html
file and,
remove the lodash <script>
, as we now import it as a dependency,
and modify the other <script>
tag to load the bundle, instead of the raw ./src file:
Update the index.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Getting Started</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>
In this setup, index.js
explicitly requires lodash to be present, and binds it to _
.
This means no global scope pollution.
When you state what dependencies a module needs, webpack can use this to build a dependency graph. Then the graph is used to generate an optimized bundle, where scripts will be executed in the correct order.
Let's run this application with npx webpack
. When you open the index.html in the dist folder in your browser.
The output should be the same as before.
The npx webpack
will take our script at src/index.js
as the entry point,
and will generate dist/main.js
as the output. The npx command (Node v8.2 or higher),
runs the webpack binary in ./node_modules/.bin/webpack
from the installed webpack package.
Thanks for reading and if you have any questions, use the comment function or send me a message @mariokandut.
If you want to know more about Node, have a look at these Node Tutorials.
Webpack, StackShare, NodeJS, NPM, Smashing Magazine, Tania Rascia
Never miss an article.