blog.jakoblind.no

How to get an error overlay with React Hot Loader

A few days ago, a new version of Create React App was released with many new features.

One of the new features released was an improved runtime error overlay. In the overlay you can see useful information such as the stack trace and error information, like this:

react error overlay for create-react-appImage from https://facebook.github.io/

With this error overlay, you know instantly if there is an error without having to look in the console. This feature really speeds up development!

But what should you do if you don’t use create-react-app? You still want that nice looking error overlay while developing, don’t you?

If you are using React Hot Loader I have some good news for you. In the latest version of webpack-dev-server, which is used by React Hot Loader, there is built in support for this sweet react error overlay.

How to enable react error overlay for React Hot Loader

First, make sure you are using version 2.2.1 of webpack-dev-server. If you don’t, upgrade.

There are two ways to run webpack-dev-server: With the Command line interface (CLI), or with Javascript code. I will describe how to enable it for both ways.

If you are using Javascript Code

Open the Javascript file you are using to start webpack-dev-server. Add overlay: true  in the config parameter. It would look something like this:

new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    overlay: true,
})

If you are using the CLI

The CLI does not accept an —overlay  flag as parameter. What you have to do is to add the following to your webpack.config.js :

devServer: { overlay:true },

An example can be found here

The result

Then when you get a runtime error, you will see an overlay in your browser that looks something like this:

It’s almost as good as Create React App!

Enable it for both warnings and errors

This gives an error overlay when there are errors. If yo want to enable this for both errors and warnings you can add the following to the config instead:

overlay: {
  errors: true,
  warnings: true
}

If you like this tip and want more like it in the future, don’t hesitate to signup to my newsletter below!


tags: