Swastik Yadav

S Y

Navigate back to the homepage

Webpack, The clear and concise explanation

Swastik Yadav
January 26th, 2024 · 2 min read

If you have been working with JS for a while, you must have came across webpack. Might have used it as well, but didn’t actually know what it does.

At least for me it didn’t made sense when I first tried it. I just copied & pasted config files from internet and somehow made it to work.

Infact that is the reason for tools like “create-react-app” to exist. Because it was too complex for beginners to setup a React app from scratch with webpack.

So, let’s understand what’s the deal with webpack.

We are going to build a small Product-Listing app and understand webpack in the proccess.

Initiating Product-Listing App.

Let’s start by setting up our project folders.

1mkdir productList
2cd ./productList
3mkdir public src

We will work with “src” and “pulic” folders later. For now we will initiate vanilla JS project.

1npm init

The above command will ask few questions, just accept all default configs. Now we have a package.json file in our project.

Installing Dependencies

Run the following command in project directory. We will talk about each dependency later.

1npm install faker html-webpack-plugin webpack webpack-cli webpack-dev-server

Adding entry HTML and JS files.

1cd ./public
2touch index.html
3// This simply creates index.html file in public folder.

Inside the public/index.html all we need to do is add a root element.

1<html>
2 <body>
3 <div id="root"></div>
4 </body>
5</html>

Now we add “index.js” inside src folder.

1cd ./src
2touch index.js
3// This simply creates index.js file inside src.

Inside src/index.js import “faker” and console a fake productName. Faker just provides some fake data to work with. Nothing fancy here.

1import faker from "faker";
2
3const productName = faker.commerce.productName();
4
5console.log(productName, "pn++");

Okay, now if we try to execute this file in terminal. We will get an error. You can add this js file as script in index.html but that’s not what we want. Neither that will be able to import faker from node_modules.

By the way we can execute the above file with “CJS require”. But instead let’s just make the “ESM import” work with webpack.

Webpack Configuration

Create a new file webpack.config.js in the root of project directory.

1touch webpack.config.js

Now let’s configure webpack and understand the installed packages.

1// Require HtmlWebpackPlugin
2const HtmlWebpackPlugin = require("html-webpack-plugin");
3
4module.exports = {
5 // mode will change to "production" in `webpack.prod.js`
6 mode: "development",
7 // port where our main.js will become available.
8 devServer: {
9 port: 8081,
10 },
11 plugins: [
12 new HtmlWebpackPlugin({
13 // Whatever file names coming out from webpack will be used as the entry point.
14 // And will be added as script to the template (public/index.html).
15 template: "./public/index.html",
16 })
17 ],
18}

webpack-dev-server

WebpackDevServer takes main.js (output by webpack) and makes it available to the browser.

html-webpack-plugin

HtmlWebpackPlugin takes whatever file name webpack generates (main.js) and adds it as script in /public/index.html.

Change the start script in package.json.

1//...rest of code...
2"scripts": {
3 "start": "webpack serve"
4 }
5//...rest of code...

Run the start script.

1npm run start

Now the main.js is available on the browser. Open http://localhost:8081/main.js in browser. We can see the source code generated by webpack. If we search we will find our productList code and faker package as well in this file.

mainjs on browser

Hmm, nice. Now just open http://localhost:8081. This will serve index.html file with main.js added as script in html file.

Open console and see the productName appear there. Let’s show productName on the screen. Make following changes in src/index.js.

1import { faker } from "@faker-js/faker";
2
3const rootElm = document.querySelector("#root");
4
5function mount(elm) {
6 let products = "";
7
8 for(let i = 0; i < 3; i++) {
9 const productName = faker.commerce.productName();
10 products += `<div>${productName}</div>`;
11 }
12
13 elm.innerHTML = products;
14}
15
16mount(rootElm);

Checking http://localhost:8081 on browser should show product lists on the screen.

Alright, let’s see some explanation around webpack.

Webpack Explanation

Normally we would have to load many different files on the browser. For ex, if our application uses multiple files and external libraries. We would have to load each file on the browser.

As a rule of thumb, we should not load many diff files on browser. And that’s where webpack comes in.

Webpack combines/bundles all those files into single file which can be loaded on the browser.

webpack-usecase

main.js/bundle.js not only contains our src/index.js code but all other imported dependency code as well.

Webpack officially calls themselves a “module bundler”. Not only scripts, but it helps you bundle styles and assets as well.


So, that is all for this post. Hopefully this was a good read for you.

Thank You!

More articles from Swastik Yadav

🛑 STOP thinking about React lifecycle methods.

In this post let's talk about the paradigm shift from lifecycle methods to state synchronization and hooks in ReactJs.

July 22nd, 2023 · 1 min read

How map() and reduce() Array method works in JavaScript.

Today let's implement our own version of the **map()** and **reduce()** array methods in JavaScript.

June 18th, 2023 · 2 min read

DiaryOfADev, Success stories of underdog developers.

Every week we share an underdog developer's story and a deep dive into a programming concept.

© 2021–2024 Swastik Yadav
Link to $https://github.com/SwastikyadavLink to $https://www.linkedin.com/in/swastikyadav/