Setup a modern JavaScript project with Webpack 5

6 min read

Setup a modern JavaScript project with Webpack 5

If haven't heard anything about webpack then from the official docs, "Webpack at its core is just a static module bundler for javascript apps." It means that webpack will combine all the modules of your project into single or multiple files. These files will contain every asset your project needs to serve the content onto production.

We will start by creating a demo javascript application.

Basic setup

To create a new folder named demo-app, open your terminal and write the following command:

mkdir demo-app

Change the directory to this demo-app folder

cd demo-app

Open this into your favorite text editor like VS Code by running:

code .

Now we need to initialize the project as an npm project. It will help us in managing tasks like our project and other javascript libraries which we are going to use.

Before going ahead, you need to have nodejs installed on your computer

npm init

The above command can be considered as the starting point of our application development process. On entering, it will ask you some questions about the project. On completing, you will find out a new file named package.json is created. This file is the heart of our app. It contains all the useful information about the project.

It is a good practice to place all of the source code into a separate folder inside the project, so we will create a new src folder inside demo-app

mkdir src

Create a new file index.js inside src/js. This will be the starting point of our application.

Normally you won't have just a single javascript file. So it's better to add all of the javascript into a separate folder.

Installing Webpack & other dependencies

What we are trying to do is to add a build step for our project which will build a final version of our app that we can serve to the client. For that, we'll start by installing some packages from the npm.

npm i -D webpack webpack-cli webpack-dev-server

This will install webpack, webpack-cli and webpack-dev-server as development dependencies.

We need webpack-cli because we are going to set up our custom configuration file and it will provide us some set of commands that will make that easier.

webpack-dev-server provides live reloading while developing the app.

What the hell is node_modules?

After the installation finishes, you might have noticed that a new folder named node_modules is created.

For short, it is the home for all of the code that you just downloaded from the npm. And you can then refer to a specific module inside your application from there.

Don't forget to add node_modules into a .gitignore file. This will make sure that the folder is not added to a version control system like git.

Configuring webpack

Before that, let's first create add some javascript so that webpack will have something to bundle. It's not useful to bundle just one javascript file.

Create a new javascript file hello.js which will have a simple function that takes a string and logs it on the console window. We are going to call this function inside index.js to print hello from index.js onto the console window.

hello.js
export const hello = (str) => {
    console.log(str);
}
index.js
import { hello } from "./hello";

hello('hello from index.js');

Create webpack config file

Create a new file named webpack.config.js at the root of our project. We'll create a really basic configuration that will create a bundle at dist folder of our app.

webpack.config.js
const path = require("path");

module.exports = {
    mode: "development",
    entry: {
        main: "./src/js/index.js"
    },
    output: {
        filename: "js/main.js",
        path: path.resolve(__dirname, "dist")
    }
}
  • By default, the mode is set to production, but we set the mode to development so that we can see webpack in action.
  • entry is the point from where our starts executing.
  • output contains configurations related to how webpack will emit the end bundle and code. It uses an absolute path and creates a dist folder to have all of the final code.

Template HTML file

We need to link the final javascript bundle into an HTML file to see it in the browser. Create a new file index.html at the root of src directory. We don't have to add the script tag ourselves in the HTML file, we will configure webpack to do that for us.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Set up a mordern javascript project with webpack 5</title>
</head>
<body>
    
</body>
</html>

Installing our first plugin

"Plugins are the backbone of webpack". They help us do all kinds of things like the one we are going to do, i.e, to automatically add the script tag in our HTML file.

We are going to install html-webpack-plugin to help us do that. Run the following command inside your terminal.

npm i -D html-webpack-plugin

Now in our config file, we are going to require that and create a plugins property.

webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: "development",
    entry: {
        main: "./src/js/index.js"
    },
    output: {
        filename: "js/main.js",
        path: path.resolve(__dirname, "dist")
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: './src/index.html'
      })
    ]
}

This is how we use plugins, you have to use the new keyword.

And we are done with configuring webpack 🎉 (for now 😬), but now how do we tell it to produce the build? For that, we need to add a script inside our package.json file.

package.json
{
    //... 
    "scripts": {
        "start": "webpack --config webpack.config.js"
    },
    //...
}

Now on running npm start into the terminal will produce the build inside dist folder. If you open the build HTML file, then you should be able to see the log message on the console window. And that brings us to the end of this article.

Linking the project we worked on, feel free to play around with it.

If you found this article helpful, I would be grateful for your support.
"Buy me some paneer curry"

Comments

I'd love to read your thoughts on this article!!!