Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing historyApiFallback for webpack-dev-middleware

I am using an express server for dev. I am using webpack-dev-middleware for the webpack config. I want to implement the equivalent of historyApiFallback using express.

historyApiFallback is available with webpack-dev-server. Whenever there is a 404 error, it will ignore sending a 404 and let the client handle the routing via history api.

How can I get it to work with express and webpack-dev-middleware?

const webpackMiddleware = require('webpack-dev-middleware');
const webpack = require('webpack');
const webpackConfig = require('../webpack.config.js');
app.use(webpackMiddleware(webpack(webpackConfig), { publicPath: '/' }));
like image 249
vijayst Avatar asked Dec 07 '17 13:12

vijayst


1 Answers

@MrBar comment is the right answer to this issue.

Here is what I did to make Express serve index.html in any 404 error:

  const webpackConfig = require("./config/webpack.dev.js")
  const compiler = webpack(webpackConfig)
  const wdm = webpackDevMiddleware(compiler, {
    noInfo: true,
    publicPath: webpackConfig.output.publicPath,
  })

  // MrBar answer.
  app.use((req, res, next) => {
    if (!/(\.(?!html)\w+$|__webpack.*)/.test(req.url)) {
      req.url = '/' // this would make express-js serve index.html
    }
    next()
  })

  // the next middleware is webpack-dev-middleware
  app.use(wdm)

  app.use(require("webpack-hot-middleware")(compiler, {
    log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000
  }))
like image 200
shackra Avatar answered Sep 28 '22 05:09

shackra