使用webpack-dev-middleware实现historyApiFallback

7
我正在使用express服务器进行开发。我正在使用webpack-dev-middleware来配置webpack。我想使用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: '/' }));

7
我曾经通过重写所有非资源URL来解决这个问题。大致代码如下: (在开发中间件之前)app.use((req, res, next) => { if (!/(\.(?!html)\w+$|__webpack.*)/.test(req.url)) { req.url = '/'; } next(); }); - MrBar
@MRar 这应该是一个答案,我认为。 - Vlad Nicula
1个回答

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
  }))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接