DEV Community

Cover image for What are Module Bundlers ? How to configure Webpack ?
Sumanth
Sumanth

Posted on • Updated on

What are Module Bundlers ? How to configure Webpack ?

Hey! 🐱

How can we take advantage of Module Bundlers to build large scale applications.

First let's understand when Module Bundlers can be used and why should we use them.

Def :- Module Bundlers can be used to bundle our JavaScript files, images, styles, and fonts together into single folder.

Clone this repo and write your code on new branch.






🌼

When we are beginners in Web Development World we use these basic 3 things : HTML, CSS, JS. But when we dive into it we might replace JS with TypeScript, HTML with Library like ReactJs, CSS with Sass.

In addition to the above things we might also inject things like firebase, npm packages, D3 Js etc. Many of the injected dependencies might use common Js which isn't going to work with modern es syntax. And we get errors like - Uncaught Reference Error : require is not defined. Some of the old browsers can't understand the new Js syntax.

So even if we try to manage the things to get it work we might end up with a massive JS file which then needs to be minified and broken into smaller files to reduce the load time.

So to solve all the above problems module bundlers like Webpack, parcel, rollup, snowpack etc., came into existence to make the process easy and error free.
Okay, now we know why these are introduced but the basic thing they do is taking multiple JS files and combine them into a single large file. which can be used later to load our app in browser.

Okay enough theory! Let's 🛠️ configure Webpack from scratch and write some code (>‿◠)✌

🌻 Follow the below steps to configure Webpack.

1. Create an entry Javascript file

Create index.js in the src folder. This src/index.js will be the entry file because everything starts from here.

// src/index.js
console.log(
"lets use lodash package to convert this plain text to kebab-case text"
);
Enter fullscreen mode Exit fullscreen mode

Now create public/index.html file and import the index.js file in it.
Folder structure 👇🏻
folder structure
index.html

<!-- public/index.html -->
<head>
    <meta charset="UTF-8">
    <title>Configure Webpack</title>
    <script src="../src/index.js"></script>
</head>
<body>
    <p>and some text here</p>
</body>
Enter fullscreen mode Exit fullscreen mode

Open the html file and you should see the console :
console output

2. Install lodash npm package

Before installing the lodash package let's first create package.json file in the project folder using the command npm init -y.
🌻
Now, Install lodash using command npm i lodash.
So now import any dependency from lodash. Let's import kebabCase to convert the normal string into kebabCase.

// src/index.js
import { kebabCase } from "lodash";

console.log(
kebabCase("lets use lodash package to convert this plain text to kebab-case text")
);
Enter fullscreen mode Exit fullscreen mode

When you hit the refresh button in the browser you should see the below error.
module import error
So this is where webpack came to the rescue and solves the above error.

3. Installing & Configuring Basic webpack

So to solve the above error we need to use bundlers like webpack, Parcel. Let's see how we can use webpack to clear the above error. Install it using the command
npm install --save-dev webpack webpack-cli.
After install webpack lets change the build command in the package.json file. Build command simply calls the webpack.

{
.
.
.
 "scripts": {
    "build": "webpack"
  },
.
.
.
Enter fullscreen mode Exit fullscreen mode

🙌🏻 Now let's run the build command npm run build from the command line. It will analyze the index.js code and then it will compile it to dist/main.js file. So to use that main.js file we need to change the script tag in html file to <script src="../dist/main.js"></script>.
Now the error in the browser should be gone and the console output should be look like this.
error free console output

🎉 And that's it we just completed configuring basic Webpack.

4. Customize the Webpack Config

Till now we are using the default Webpack config. Default config will look for src/index.js file by default. So if the name of the file is other than index.js things will not work.
So to craft our own configuration we need a file. Create webpack.config.js file in the root directory. Then you can start customizing the behavior of Webpack.

const path = require("path");
module.exports = {
  // define your entry point here
  entry: "./src/index.js",
  output: {
    filename: "otherThanMain.js",
    path: path.resolve(__dirname, "dist"),
  }
};
Enter fullscreen mode Exit fullscreen mode

Now run the build command again and otherThanMain.js will be created inside the dist folder. Because we changed the output file name in the config file.

5. Adding Sass loader

But when building the big projects we might also use the Sass. So create style.scss file inside the src folder and write some sass code and then import it insider the index.js file.

import "./style.scss";

import { kebabCase } from "lodash";

console.log(kebabCase("lets use lodash package to convert this plain text to kebab-case text"));
Enter fullscreen mode Exit fullscreen mode

Since we are importing the sass file inside our js file things will not work. So to make the things work we need to install SASS Loader*. Loaders can be used to process the files that aren't Javascript.

Run the command npm i --save-dev css-loader style-loader sass-loader. Right after installing them modify the webpack config file like this :

const path = require("path");
module.exports = {
  entry: "./src/index.js",
  output: {
    filename: "awesome.js",
    path: path.resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
        test: /\.s[ac]ss$/,
        use: [
          // Creates `style` nodes from JS strings
          "style-loader",
          // Translates CSS into CommonJS
          "css-loader",
          // Compiles Sass to CSS
          "sass-loader",
        ],
      },
    ],
  },
};
Enter fullscreen mode Exit fullscreen mode

Now run the build command again and everything will be alright.

Learn more about module bundlers and webpack here.
My twitter handler - @movingmelody
Tutorial video ref.
Access files from here -




Top comments (0)