DEV Community

Mario
Mario

Posted on • Originally published at mariokandut.com on

Getting started with Webpack

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.

"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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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());
Enter fullscreen mode Exit fullscreen mode

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/lodash@4.17.20"></script>
  </head>
  <body>
    <script src="./src/index.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

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"
  }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

To bundle the lodash dependency with index.js, we'll need to install the library locally:

npm install lodash
Enter fullscreen mode Exit fullscreen mode

After installing it, lodash has to be imported. Add the following code to index.js:

import _ from 'lodash';
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)