Getting started with Webpack
© https://webpack.js.org/

Getting started with Webpack

Deep dive into webpack and what problems it can solve for you

ByMario Kandut

honey pot logo

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.

What is Webpack?

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.

Code example

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.htmlfile, 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:

  • It is not immediately apparent that the script depends on an external library.
  • If a dependency is missing, or included in the wrong order, the application will not function properly.
  • If a dependency is included but not used, the browser will be forced to download unnecessary code.

Don't worry. There is a solution to all these problems. Webpack can manage this instead, and create a bundle.

How to create a bundle with webpack

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.

TL;DR

  • Webpack is a static module bundler for modern JavaScript applications.
  • Webpack builds a dependency graph from points and then combines every module your project needs into one or more bundles, which are static assets to serve your content from.
  • Use webpack to bundle your application and don't worry about global scope pollution, missing dependencies, installed but not used dependencies, wrong order of imports or implicit dependencies (which you are not aware of) anymore.

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.

References (and Big thanks):

Webpack, StackShare, NodeJS, NPM, Smashing Magazine, Tania Rascia

More node articles:

Getting started with Webpack

How to list/debug npm packages?

How to specify a Node.js version

How to create a web server in Node.js

How to dynamically load ESM in CJS

How to convert a CJS module to an ESM

How to create a CJS module

How to stream to an HTTP response

How to handle binary data in Node.js?

How to use streams to ETL data?

How to connect streams with pipeline?

How to handle stream errors?

How to connect streams with pipe?

What Is a Node.js Stream?

Handling Errors in Node (asynchronous)

Handling Errors in Node.js (synchronous)

Introduction to errors in Node.js

Callback to promise-based functions

ETL: Load Data to Destination with Node.js

ETL: Transform Data with Node.js

ETL: Extract Data with Node.js

Event Emitters in Node.js

How to set up SSL locally with Node.js?

How to use async/await in Node.js

What is an API proxy?

How to make an API request in Node.js?

How does the Event Loop work in Node.js

How to wait for multiple Promises?

How to organize Node.js code

Understanding Promises in Node.js

How does the Node.js module system work?

Set up and test a .env file in Node

How to Use Environment Variables in Node

How to clean up node modules?

Restart a Node.js app automatically

How to update a Node dependency - NPM?

What are NPM scripts?

How to uninstall npm packages?

How to install npm packages?

How to create a package.json file?

What Is the Node.js ETL Pipeline?

What is data brokering in Node.js?

How to read and write JSON Files with Node.js?

What is package-lock.json?

How to install Node.js locally with nvm?

How to update Node.js?

How to check unused npm packages?

What is the Node.js fs module?

What is Semantic versioning?

The Basics of Package.json explained

How to patch an NPM dependency

What is NPM audit?

Beginner`s guide to NPM

Getting started with Node.js

Scroll to top ↑