Why module bundlers?

Why module bundlers?

What and why of module bundlers.

·

2 min read

A JavaScript bundler is a tool that puts your code and all its dependencies together in one JavaScript file.

To better understand this concept let's build a simple application, where we toggle the visibility of a paragraph on click of a button.

Let's place our elements in index.js

<!DOCTYPE html>
<html>
  <head>
    <title>Toggle Visibility</title>
    <style>
      .d-none {
        display: none !important;
      }
      .d-block {
        display: block !important;
      }
    </style>
  </head>

  <body>
    <div id="app">
      <p class="d-none" id="toggle-paragraph">This is a paragraph</p>
      <button id="toggle-btn">Toggle Visibility</button>
    </div>
    <script src="https://unpkg.com/jquery@1.12.4/dist/jquery.js"></script>
    <script src="src/index.js"></script>
  </body>
</html>

Using jquery, we write the logic to toggle visibility in src/index.js

const toggleButton = $("#toggle-btn");
console.log("Toggle ", toggleButton);
toggleButton.click(() => {
  $("#toggle-paragraph").toggleClass("d-block");
});

Everything works great.

https://d3dyfaf3iutrxo.cloudfront.net/general/upload/e30a28f6a9bf45d5935be3c78e26336c.gif

Now, let's make a small change and change the order of script tags in index.html file.

https://cdn.hashnode.com/res/hashnode/image/upload/v1634156112085/qxfGriReV.png

What happens now?

You get an error which says

Reference Error: $ is not defined.

Why?

This happens because of the dependency between Javascript files.

https://cdn.hashnode.com/res/hashnode/image/upload/v1634156341693/m9kFGWT6l.png

This is the case with just two files.

What happens when there are 1000s of files?

One of the solution can be merge all the files into single file. This can be achieved by using Gulp or any other tool. But, maintaining configuration for the same is a tedious task.

We need a tool that recognizes the dependencies and combines the files maintaining the dependency order.

This is exactly what Javascript module bundler does. Webpack , Parcel, rollup are some of the examples of Javascript module bundler.