Module Bundlers Introduction

Akshay Bhargava
3 min readNov 11, 2021

--

Do you want to a quick overview and setup for module bundler (webpack) ?. If yes then this story is for you.

So, What is a module bundler ?

A module bundler is a simple and useful tool that collects pieces of JavaScript and their dependencies into a single file. THAT’S IT !.

Why use a module bundler ?

To take advantage of Tree- shaking we align to use a module bundler. It is the job of a module bundler to bundle our different pieces of imported source code together into a single JavaScript file. And this final bundled file is the one that we link to out HTML page.

Tree Shaking ?

Remove unused export from injected libraries

Tree shaking is only a small portion of the wide reasons to use a module bundler. But it is worth noting that tree shaking comes out to be significant configuration that you need to keep in mind to make your website more performance efficient.

Setting up a module bundler. — Webpack

In an empty folder we usually start with a “source” / src folder and a dist folder. The src folder is the one where we write all our JavaScript logic and the dist is the one where our final version of the bundled JS file is located.

I am going to use to npm to install our dependencies, webpack in this scenario.

Step 1: Initialize your package.json file

npm init -y

Step 2: Install webpack

npm install webpack -D webpack-cli

Note — Webpack cli is installed as a dev dependencies.

Step 3: Create webpack file

Create a new file webpack.config.js. It is worth noting that this file needs to be at the root level of your project structure. Now we need to instr4uct what we need webpack to do. This file will export an object that defines our webpack configuration.

Step 4: Writing webpack configuration

The path is a core node package and we use it define and use out file structure. The watch property set to true will make sure that every time we save our file the webpack config file makes sure to bundle the updated code automatically.

A point to remember that path property of output object needs to be an absolute path.

Step 5: Run / Use Webpack

In our package.json file we need to set property in scripts object to use webpack. I will call mine “build” but can be different according to various usages.

"scripts": {   "build": "webpack"},

Now every time we run npm run build, webpack will do it’s job.

Step 6: Link bundle.js to your index.html file

These are all the simple steps that you actually need to setup a basic webpack setup. When you run npm run build command, since it is in watch mode it will automatically look for changes in index.js file. If you require other JavaScript file in your index.js file then again webpack will bundle them and it will be ready to use in your index.html file.

--

--