If we want to update our code (say, to change our h1 to h2), we’ll have to make the change, rerun yarn build, and then reload the page for every single change we want to see. That’ll slow us down a lot in our development process.
Ideally, every time we change our JavaScript, the Webpack command will automatically rerun, and will reload the page. What a world of luxury that would be!
Fortunately, there’s a package called webpack-dev-server for exactly this purpose. To install it, just run yarn add webpack-dev-server.
Before we jump in, let’s briefly cover how the Dev Server works. It runs a small Node application in the background of our machine, serving up the files in our public folder so that we can see them by visiting localhost:3000 in our browser. At the same time, it watches the source files of the bundle.js, rebundles them when they change, and then reloads the page.
To get it to work, we need to specify which folder we want to serve up (public), and then do some basic configuration.
In our webpack.config.js, add the following before the closing squiggly bracket (we have the full code here):
contentBase does this, setting public as the folder to serve, historyApiFallback lets our single-page app seem like a multipage app, and inline is the bit that automatically refreshes the page on file changes:
This will run our Dev Server (ensure that you ran yarn add webpack-dev-server first). In your Terminal, type in yarn start. You’ll see our Webpack compile, and a notice that our app is running on port 8080. Let’s hop over to http://localhost:8080 in our browser and we should see our application.
The last test is to change the text in our index.js from Hello from React to Hello from Webpack!. Your browser tab should automatically reload and reflect the changes, without you having to rerun the Webpack command.