Search code examples
javascriptwebpackwebpack-dev-serverhtml5-history

Using webpack dev server for Single Page App historyApiFallback without using the default index.html file


Recently I had to rename my index.html file to app.html because of some Firebase Hosting related issues.

Before that, my webpack dev server was working just fine, with the following configuration using the index.html file:

webpack.config.js

// SOME OTHER CONFIGS

entry: {
    app: './src/index.js'
  },

  plugins: [
    new CleanWebpackPlugin(),
    new WebPackManifestPlugin(),
    new HtmlWebpackPlugin({
      //title: 'Todo App',
      favicon: 'src/assets/Favicon.ico',
      template: './src/index.html',
    }),
    new Dotenv()
  ],

  devServer: {
    contentBase: './public',
    compress: true,
    hot: true,
    historyApiFallback: true,
  },

But after changing my index.html to app.html I had to update some configs to point to the new file.

webpack.config.js

// SOME OTHER CONFIGS

entry: {
    app: './src/index.js'
  },

  plugins: [
    new CleanWebpackPlugin(),
    new WebPackManifestPlugin(),
    new HtmlWebpackPlugin({
      //title: 'Todo App',
      favicon: 'src/assets/Favicon.ico',
      template: './src/app.html',                // <-------------- ADDED THIS
      filename: 'app.html'                       // <-------------- ADDED THIS
    }),
    new Dotenv()
  ],

  devServer: {
    contentBase: './public',
    compress: true,
    hot: true,
    historyApiFallback: true,
    index: 'app.html'                            // <-------------- ADDED THIS
  },

PROBLEM

And now what happens is that my dev server is only accepting the home route '/'. For every other specific routes it's responding with a 404.

https://webpack.js.org/configuration/dev-server/#devserverhistoryapifallback I guess this is the reason why:

enter image description here


QUESTION

How can I solve this? Do I need rewrites to point all the routes to my app.html file or is there an easier solution?

If I need the rewrite, how can I write one of those? I didn't get the /^\/$/ syntax of the from property. How can I write a /** wildcard route?


Solution

  • From: https://github.com/bripkens/connect-history-api-fallback

    Just found out what was missing:

    devServer: {
        contentBase: './public',
        compress: true,
        hot: true,
        // historyApiFallback: true,
        historyApiFallback: {
          index: '/app.html'                  // <----- THIS WORKS
        },
        index: 'app.html'
        // headers: {
        //   "Access-Control-Allow-Origin": "*",
        //   "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
        //   "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
        // }
      },
    

    Now everything works.