What are Module Bundlers ? How to configure Webpack ?

What are Module Bundlers ? How we can take advantage of them to build large scale applications.

Hey! ?
First let’s understand when Module Bundlers can be used.
Def :- Module Bundlers can be used to bundle our JavaScript files, images, style…


This content originally appeared on DEV Community and was authored by Sumanth

What are Module Bundlers ? How we can take advantage of them to build large scale applications.

Hey! ?
First let's understand when Module Bundlers can be used.
Def :- Module Bundlers can be used to bundle our JavaScript files, images, styles, and fonts together into single folder.

?
When we are getting started with Web Development we use these basic 3 things : HTML, CSS, JS. But when we dive into it we might replace JS with TypeScript, HTML with React Library, 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. We might get errors like - Uncaught ReferenceError : require is not defined. And even if we 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"
);

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>

Open the html file and you should see the output like :
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 the following command npm i lodash.
So now try to 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")
);

When you hit the refresh button in the browser you should see the below error.
module import 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"
  },
.
.
.

?? 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"),
  }
};

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"));

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",
        ],
      },
    ],
  },
};

Now run the build command again and everything will be alright. Learn more about module bundlers and webpack here.
Tutorial video ref.


This content originally appeared on DEV Community and was authored by Sumanth


Print Share Comment Cite Upload Translate Updates
APA

Sumanth | Sciencx (2021-06-16T17:41:58+00:00) What are Module Bundlers ? How to configure Webpack ?. Retrieved from https://www.scien.cx/2021/06/16/what-are-module-bundlers-how-to-configure-webpack/

MLA
" » What are Module Bundlers ? How to configure Webpack ?." Sumanth | Sciencx - Wednesday June 16, 2021, https://www.scien.cx/2021/06/16/what-are-module-bundlers-how-to-configure-webpack/
HARVARD
Sumanth | Sciencx Wednesday June 16, 2021 » What are Module Bundlers ? How to configure Webpack ?., viewed ,<https://www.scien.cx/2021/06/16/what-are-module-bundlers-how-to-configure-webpack/>
VANCOUVER
Sumanth | Sciencx - » What are Module Bundlers ? How to configure Webpack ?. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/16/what-are-module-bundlers-how-to-configure-webpack/
CHICAGO
" » What are Module Bundlers ? How to configure Webpack ?." Sumanth | Sciencx - Accessed . https://www.scien.cx/2021/06/16/what-are-module-bundlers-how-to-configure-webpack/
IEEE
" » What are Module Bundlers ? How to configure Webpack ?." Sumanth | Sciencx [Online]. Available: https://www.scien.cx/2021/06/16/what-are-module-bundlers-how-to-configure-webpack/. [Accessed: ]
rf:citation
» What are Module Bundlers ? How to configure Webpack ? | Sumanth | Sciencx | https://www.scien.cx/2021/06/16/what-are-module-bundlers-how-to-configure-webpack/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.