What is WebPack and What are Modules?

Search for a command to run...

No comments yet. Be the first to comment.
💡 “So if you want to go fast, if you want to get done quickly, if you want your code to be easy to write, make it easy to read.” -By Robert C. Martin JavaScript has progressed a ton in recent years. If you are learning JavaScript in 2022 and you ...

Before beginning our quest to find how not to use Create React App. First, let’s see why we need Create React App in the first place. Why do we need Create React App? 🤔 Create React App is a comfortable environment for learning React and is the best...

Getting Started with Node.js In this blog, we will try to understand the basics of Node.js, how it works, and why to choose Node.js, but before diving into node let's talk a little bit about Java-script. JavaScript is one of the best programming lang...

If you are reading this, you probably know what React.js is and might have already used it Earlier. However, you might be wondering why I am reading about folder structure? Can’t I just stuff all my files in the src folder?? 🤪 Technically you could ...

Let’s first understand 🤔 What is an Array? Quoting from MDN directly. The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name and has members for performing common...

In its broadest definition: WebPack is a bundler, a module bundler. 😼
What it basically does is bundles all assets and files. 💪
To understand why WebPack is necessary, it is important to know How was Javascript used on the web before bundlers were a thing. 😶🌫️
We can use a script file, in fact using a <script> tag is the most basic way in which we all started using JavaScript.
*If an application is small say 500 lines of code, Great to use a script tag, and Voila Done. 🤩*
But then your code expands and new functionalities are added but say that your code is not just mere 500 lines.
Managing so much code all in one file is a herculean task and doing this alongside other collaborators will be a developer's nightmare. It will create problems in scope, size, readability, and maintainability. 🙄
So the solution is to split the single code file and break it into say 10 or 15 smaller files and insert 15 script tags on our page. So it’s over na? Finally. But wait here is a catch!
It is needed to see the ordering of all the script tags, making sure that the utility function is available before using it in another file. Also, the problem with global scoping is still relevant.
Now, this idea of using modularity and creating modules that can be imported or exported between different JavaScript files introduced the need to have local modules with local variables and bundling them together to give a single output file using a Bundler 🤠
Definition and Usage and pros over normal script tags
Problems with IIFE function :
<script> tag still matters.IIFE functions gave us a few ideas about modularity in Javascript. Utilizing this CommonJS was introduced which was popularized with the advent of NodeJS.
Definition and Usage
require() keyword ) in a certain way.Cons: Problems with CommonJS
So then we moved on to ES Modules which encompasses the pros of CommonJS and removes the cons.
Definition and Usage
import statements at the top of your module, the bundler can quickly understand your dependency tree. and thus enabling Tree Shaking or Dead Code Elimination.Cons: Problems with ES6 Modules
Bundles enabled us to introduce modularity in Javascript and get best practices in Javascript but what next ?
These are bundlers which not just work for JavaScript files but for any file type. 😳
This means that by using WebPack and thus this distinguishes them from common bundlers like browserify is that WebPack creates dependency graph/tree for any file type and thus enables modularity not just across JavaScript files but say also across CSS files and assets files. 🥳
WebPacks not only let us write modules but also support any module format (at least until we get to ESM) and handle resources and assets at the same time.
This is why WebPack exists. It's a tool that lets one bundle JavaScript applications (supporting both ESM and CommonJS), and it can be extended to support many different assets such as images, fonts, and stylesheets. 🤗
In plain simple words, Webpack lets you use
require()on local "static assets," meaning non-Javascript files. Webpack is a module bundler for all types of files and assets. When one runs Webpack, it searches through all of your code forrequire()calls and then creates a dependency tree. Enabling us to not only have no issues with the handling of Javascript files functions and utilities but also assist us to import images and CSS.
It is the starting node in a graph or say an entry point that WebPack uses to start drawing out its internal dependency tree.
WebPack figures out the other modules that depend upon the entry point whether directly or indirectly.
By default, it starts from ./src/index.js, but it can be changed to any file of choice.
Say that WebPack has created a bundle file with Javascript modules and assets. Now where to put these bundles?
The main output file is written as ./dist/main.js and other generated files can be added to the ./dist directory
We can also define the output path and output filename for the location of our output.
According to the official documentation, Loaders are transformations that are applied to the source code of a module.
Bundlers can only handle Javascript files and can only create dependency trees/graphs for these files but as WebPack enables us to generate dependencies for assets also it needs to preprocess non- Javascript files also.
And loaders are the large variety of formats that allow us to transform files from one language to javascript like reading image paths as URLs or importing CSS directly from Javascript.
It gives WebPack the ability to import .css, .svg, and other files and process them- which starts with downloading loaders. For example, to import .css and .svg files, we’ll install cssloader and svg-inline-loader respectively -
We add them as rules to our webpack.config.js
Loaders, basically, have two properties in the configuration, that are -
test property determines which file(s) should be transformed.use property specifies which loader will be used for that particular file.Plugins are used to handle asset management, bundle optimization, and usage of environment variables alongside a bundle.
Plugins perform operations after the generation of bundlers.
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: { app: "./entry.js" }, // Start bundling
output: {
path: path.join(__dirname, "dist"), // Output to dist directory
filename: "[name].js", // Emit app.js by capturing entry name
},
// Resolve encountered imports
module: {
rules: [
{ test: /\.css$/, use: ["style-loader", "css-loader"] },
{ test: /\.js$/, use: "swc-loader", exclude: /node_modules/ },
],
},
// Perform additional processing
plugins: [new webpack.DefinePlugin({ HELLO: "hello" })],
// Adjust module resolution algorithm
resolve: { alias: { react: "preact-compat" } },
};
Here we can see the configuration of a WebPack .
We see
