Skip to content

How to Setup Webpack Dev Server

In this Webpack 5 video tutorial, I’m going to show you how to set up a Webpack dev server. It will allow us to set up a development web server that will watch our project for changes. And it will automatically reload our project when things change. When you include it in your project, it will allow for the live reloading of all of your assets.

Install Webpack Dev Server

To set up the Webpack dev server, I’m going to navigate to my project directory. I’m then going to install the Webpack dev server into dev dependencies. So I will say npm install —save-dev webpack-dev-server

Configure Webpack 5 to use webpack-dev-server

Once this is installed, we can go back to our Webpack config, and we’re going to add another node called “devServer”.

We will then add a “contentBase”, which will tell the dev server where to serve the content from, and it will be set to path.join(__dirname, 'dist').

And then, we want to specify which port the server should run on. I’m going to use port 3000.

I’m then going to add another property called “open” and set it to true. It will tell the dev server to open your default browser after the server had been started.

Create an NPM Script to Run the Webpack Dev Server

So at this point, I will open up our package.json file. Let’s add another script here called “serve”, and this is going to use ./node_modules/.bin/webpack serve.

Run the Webpack Dev Server

So let’s go back over to the terminal, so I can say npm run serve, you can see that the same Webpack build steps from before are being performed, and this will tell me that the project is running at localhost:3000.

Now let’s go back to our code to ensure that this is working as expected. We’re going to open index.js, and I will make a small change in our application. Let’s set the text to “Hello from webpack-dev-server”.

So when I hit save, the Webpack dev server will detect the change, and it is going to bundle everything up again. And once the build ends up bundling, it’s going to reload this for us automatically.

So with the help of the Webpack dev server, whenever we’re working in a development environment, we don’t have to stop and restart again. It is going to help us reload all of our assets whenever they change.

GitHub Repo

Check the GitHub repository here → GitHub