How to use Webpack for blazing-fast front-end development

You may have already known that webpack is a javascript module bundler. But there’s actually more to it than meets the eye.

In reality, it has a lot of features that you may not be aware of such as HMR or Hot Module Replacement which is undoubtedly the best feature webpack has to speed up front-end development.

Webpack also has some great features such as tree-shaking. But we will not discuss it in this article.

Today, I will discuss the role and use of Hot Module Replacement in speeding up our front-end development.

What is Hot Module Replacement?

Hot Module Replacement or HMR based on webpack’s official webpage:

Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running, without a full reload. This can significantly speed up development in a few ways:

– Retain application state which is lost during a full reload.

– Save valuable development time by only updating what’s changed.

– Modifications made to CSS/JS in the source code results in an instant browser update which is almost comparable to changing styles directly in the browser’s dev tools.

From webpack’s official website

To make it short, you can basically modify your javascript files without full page reload by just updating what is changed!

Just imagine how much time would you be able to save without page refresh and just simply modify your javascript or css files to reflect your changes quickly.

Now let us start discussing on how we can achieve this.

Initializing the project

Initializing files and folders

Let us initialize the files and folders we will be using for this. To create folders that we need, open your powershell for windows or bash terminal on Mac or Linux and type this command:

mkdir src, dist

To create files, let us run the following commands (Mac, Linux):

touch index.html
touch index.js

For Windows powershell, do this:

cat > index.html
cat > index.js

Populate your index.js file with this code snippet for testing:

function component() {
    const element = document.createElement('div');

    element.innerHTML = "hello world! How are you?";

    return element;
}

let element = component();
document.body.appendChild(element);

Then populate your index.html with basic html tags and let’s move on.

Initializing package.json

First, we need to create configuration file for webpack to achieve the process. To start, type the following command:

npm init -y

This creates package.json file and allows us to install/save packages we’ve installed by using npm.

The following commands should now make your project folder look like this:

Configuring Webpack

Installing webpack packages

Now that we have package.json file, it’s time to run the following command:

npm install --save-dev webpack webpack-cli webpack-dev-server

This is responsible for your webpack to function properly. Since we will make use of webpack-dev-server in making HMR possible, we include installing the package in our project as well.

Initializing webpack.config.js

Next up is initializing our webpack config file. Create webpack.config.js and paste the following:

const path = require("path");


module.exports = {
	entry: {
		bundle: './index.js'
    },
	output: {
		path: path.join(__dirname, "./dist"),
		filename: "[name].js"
    }
};

Let us explain what’s happening in our configuration:

Entry – here lies your entry js files that webpack will bundle along with its dependencies (import, require). You can have as many entry files as you want.

Output – This is related to the output files webpack will be generating as it tries to bundle the js files into one as specified in entry object.

  • Path – Path is where the output shall be generated. In the code snippet, we were telling webpack to put the output files on dist folder.
  • Filename – This is the name of our output files. To reuse the name of the entry objects we created, use the [name] variable instead.

Now, run the command for testing:

webpack

You would probably see an output similar to this after you run the command:

After that, import your bundle.js file inside your index.html file and you would probably see the following output:

Setting up and using webpack-dev-server

In order to make use of HMR, we will be needing webpack-dev-server. To configure webpack-dev-server, we will be needing to modify our webpack.config.js a little bit again.

Copy-paste this code snippet in your webpack.config.js file:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");


module.exports = {
	entry: {
		bundle: './index.js'
    },
    devServer: {
        contentBase: "./dist",
        open: true,
        port: 3000,
        overlay: true
    },
	output: {
		path: path.join(__dirname, "./dist"),
		filename: "[name].js"
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'index.html'
        })
    ]
};

There are a couple of things to notice in the setup:

devServer – This object is responsible for setting up our webpack-dev-server library that we will be using to initiate HMR.

  • contentBase – Asks webpack-dev-server to get the files in the folder location specified in this parameter
  • open – Opens web browser when webpack-dev-server is starting up
  • port – Port address that webpack-dev-server will be using
  • overlay – Errors in javascript will be shown in a browser window which makes debugging easier when setting it to true

html-webpack-plugin – This plugin is responsible for copying html file that we’re using for front-end and use it in webpack-dev-server. You can also notice that when you run webpack and bundle javascript, the html file you specified will be copied in dist folder.

Now let us configure package.json file and put the following in scripts object:

 "watch": "webpack-dev-server" 

This allows us to just type the command npm run watch and run webpack-dev-server.

Now, let us try to run webpack-dev-server by typing the command: npm run watch. You will notice immediately that it’s running in localhost:3000 and it’s using your index.html as html file for running the localhost.

For more info on configuring webpack-dev-server, visit this link for more details.

Setting up HMR

Next is we will setup Hot Module Replacement in webpack-dev-server.

Paste the following code in webpack.config.js file:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require("webpack");

module.exports = {
	entry: {
		bundle: './index.js'
    },
    devServer: {
        contentBase: "./dist",
        open: true,
        port: 3000,
        overlay: true,
        hot: true
    },
	output: {
		path: path.join(__dirname, "./dist"),
		filename: "[name].js"
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'index.html'
        }),
        new webpack.HotModuleReplacementPlugin()
    ]
};

Now, let us try using vanilla javascript and use HMR. Put the following code snippet inside index.js:

import myComponent from './src/myComponent.js';


function component() {
    const element = document.createElement('div');

    element.innerHTML = "Hello world! How are you?";
    element.appendChild(myComponent());

    return element;
}

let element = component(); // Store the element to re-render on myComponent.js changes
document.body.appendChild(element);

if (module.hot) {

    module.hot.accept('./src/myComponent.js', function () {
        console.log('Accepting the updated myComponent module!');

        document.body.removeChild(element);
        element = component(); // Re-render the "component" to update the click handler
        document.body.appendChild(element);
    })
}

Then create src folder and create myComponent.js inside it. Once done, paste this code snippet:

module.exports = () => {
    const h1 = document.createElement("h1");
    h1.innerHTML = "Change me!";


    return h1;
}

After this, type the command npm run watch again. Then you will see this page:

Noticed at the bottom you see the console showing the message [WDS] Hot Module Replacement enabled. which means we successfully activated HMR in webpack-dev-server.

At your command prompt you will also see the following:

Let us try modifying myComponent.js and see what happens. Change its innerHTML property and press save. After that your page should look like this:

You will see that the page didn’t reload entirely but just loaded specific javascript file we’ve modified and refreshed some parts of the DOM.

Conclusion

I hope you learned a lot and enjoyed reading the article. Let me know if you’ve encountered bugs and issues in my tutorial.

Next tutorial will tackle using HMR in React apps. Stay tuned!

A Software Engineer who loves to code and write articles.

Leave a reply:

Your email address will not be published.

Site Footer