How to package nodejs application using webpack

April 06, 2022

In this article i will explain you step by step to package your nodejs application with webpack, webpack generally helps in creating build and bundling up the project application files to avoid unneccessary file loading and thus increase performance

Step 1: Install WebPack

Navigate to your nodejs application folder and run below command, we will install webpack as development dependencies

npm install --save-dev webpack webpack-cli

Step 2: Create WebPack configuration file

Under root path of your project folder create file webpack.config.js

Copy paste below code

const path = require("path");

module.exports = {
  mode: "development",
  entry: "./src/app.js",
  output: {
    filename: "app.js",
    path: path.resolve(__dirname, "assets", "scripts"),
    publicPath: "assets/scripts/",
  • In above code mode:“development” here we can tell webpack whether we are in development mode or production mode and webpack will create the application bundle accordingly.

  • In above code entry:“./src/app.js” is the entry point means main file of your nodejs application from which you start the node server. you can change the path according to your application folder and file structure

  • output:{filename:“app.js”} this is the single ouput file which webpack will generate after bundling all the dependencies file

  • output:{path:path.resolve(__dirname,“assets”,“scripts”)} this is the output path where app.js js file will generated by webpack after bundling all the dependencies. you can change the path according to your application requirement

  • output:{publicPath: “assets/scripts/“} this is the path where in if suppose you are using and importing any extra file like images, external script then you need to mention the path of those files where you have kept these public images and scripts

Step 3: Change package.json and add webpack command

In order to use package.json go to package.json file and add a command for webpack under scripts section


Run the below command to start the webpack build

npm run build

Step 4: Using Webpack dev server

Webpack dev server creates development bundle and also helps in serving our application and it reloads the development server whenever we change something in our code

Install the Webpack dev server using below command

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

Once installed we can use the Web pack dev server to serve our application we need to update our package.json and add some configuration


Run the below command to start the development server using webpack-build-server this command will be running and detecting any change in the file

npm run build:dev