Backbencher.dev

Setup Webpack Dev Server in React Project

Last updated on 25 Apr, 2022

We have a React project. We can build the project using Webpack. We can then see the output by running the generated bundle. Each time, when we change anything in the code, we need to repeat the build and reload step. That is quite boring and time consuming during development.

Webpack Dev Server helps developers by automatically building the project and reloading the page in browser. So, when we save the code, we can see the change instantly on the browser.

Some Background

I am working on a personal project, which is a Tambola game. I have already:

Next step is to setup Webpack Dev Server in my project. That is what I am documenting here. At any time, you can check the status of my development site here.

Dev Server Setup

First, we need to install webpack-dev-server in our project.

npm install --save webpack-dev-server

Configuration

Next, we need to update webpack.config.js to set dev server options. Append the below code to module.exports.

devServer: {
    static: {
      directory: path.join(__dirname, 'dist'),
    },
    compress: true,
    port: 9000,
  },

Above configuration serves the content from /dist folder.

Running

We want our dev site to run locally on npm run dev command. For that, add a dev script to package.json.

"dev": "webpack-dev-server --open"

The --open flag is to open the site in our default browser.

Try running the dev command. The site will be served from http://localhost:9000. Go and update content of our React component and save the file. Automatically, webpack-dev-server will build and update our page in browser.

--- ○ ---
Joby Joseph
Web Architect