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/[email protected]/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
COPY
const toggleButton = $("#toggle-btn"); console.log("Toggle ", toggleButton); toggleButton.click(() => { $("#toggle-paragraph").toggleClass("d-block"); });
Everything works great.
Now, let's make a small change and change the order of script
tags in index.html
file.
You get an error which says
Reference Error: $ is not defined.
Why?
This happens because of the dependency between Javascript files.
This is the case with just two 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.