How to tell webpack dev server to serve index.html for any route How to tell webpack dev server to serve index.html for any route reactjs reactjs

How to tell webpack dev server to serve index.html for any route


I found the easiest solution to include a small config:

  devServer: {    port: 3000,    historyApiFallback: {      index: 'index.html'    }  }

I found this by visiting: PUSHSTATE WITH WEBPACK-DEV-SERVER.


historyApiFallback option on official documentation for webpack-dev-server explains clearly how you can achieve either by using

historyApiFallback: true

which simply falls back to index.html when the route is not found

or

// output.publicPath: '/foo-app/'historyApiFallback: {  index: '/foo-app/'}


Adding public path to config helps webpack to understand real root (/) even when you are on subroutes, eg. /article/uuid

So modify your webpack config and add following:

output: {    publicPath: "/"}devServer: {    historyApiFallback: true}

Without publicPath resources might not be loaded properly, only index.html.

Tested on Webpack 4.6

Larger part of config (just to have better picture):

entry: "./main.js",output: {  publicPath: "/",  path: path.join(__dirname, "public"),  filename: "bundle-[hash].js"},devServer: {  host: "domain.local",  https: true,  port: 123,  hot: true,  contentBase: "./public",  inline: true,  disableHostCheck: true,  historyApiFallback: true}