为webpack-dev-middleware实施historyApiFallback

问题描述 投票:5回答:1

我正在为开发人员使用快递服务器。我正在为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: '/' }));
express webpack browser-history
1个回答
0
投票

@ 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
  }))
© www.soinside.com 2019 - 2024. All rights reserved.