为webpack-dev-middleware实施historyApiFallback

vij*_*yst 5 browser-history express webpack

我正在为开发人员使用快递服务器。我正在为webpack配置使用webpack-dev-middleware。我想使用express实现等效的historyApiFallback。

historyApiFallback可用于webpack-dev-server。每当出现404错误时,它都会忽略发送404错误,并让客户端通过历史API处理路由。

如何使它与Express和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: '/' }));
Run Code Online (Sandbox Code Playgroud)

sha*_*kra 1

@MrBar 评论是这个问题的正确答案。

以下是我为使 Express 在任何 404 错误中提供 index.html 所做的操作:

  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
  }))
Run Code Online (Sandbox Code Playgroud)