【问题标题】:Implementing historyApiFallback for webpack-dev-middleware为 webpack-dev-middleware 实现 historyApiFallback
【发布时间】:2018-05-21 15:20:12
【问题描述】:

我正在使用快速服务器进行开发。我正在为 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: '/' }));

【问题讨论】:

  • 我曾经通过重写所有非资源 url 解决了这个确切的问题。像这样:(在开发中间件之前)app.use((req, res, next) => { if (!/(\.(?!html)\w+$|__webpack.*)/.test(req.url)) req.url = '/'; next() });
  • @MRar 这应该是 imo 的答案。

标签: express webpack browser-history


【解决方案1】:

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

这是我为在任何 404 错误中使 Express 服务 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
  }))

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 2017-07-06
    • 2017-12-20
    • 2020-09-28
    • 1970-01-01
    • 2017-11-28
    • 2019-04-22
    • 2018-11-26
    • 2018-04-26
    相关资源
    最近更新 更多