在 webpack-dev-server 的 historyApiFallback` 中匹配根路由

the*_*ott 4 reactjs webpack webpack-dev-server webpack-dev-middleware create-react-app

演示该问题的示例回购在这里。

我正在尝试设置 webpack 开发服务器,以便:

  1. 请求/public/landing.html(静态登录页面)提供服务
  2. 对其他任何事物的请求由我的 React 应用程序提供

使用create-react-app, 并基于webpack-dev-server's options,我设置webpackDevServer.config.js如下:

historyApiFallback: { // Paths with dots should still use the history fallback. // See https://github.com/facebookincubator/create-react-app/issues/387. disableDotRule: true, rewrites: [ // shows views/landing.html as the landing page { from: /^\/$/, to: 'landing.html' }, // shows views/subpage.html for all routes starting with /subpage { from: /^\/subpage/, to: 'subpage.html' }, // shows views/404.html on all other pages { from: /./, to: '404.html' }, ], },

当我启动 webpack 时,我看到的是:

  • 请求/subpage被正确路由到subpage.html
  • 对 的请求/foo正确路由到404.html。最终,这些将由我的 React 应用程序处理。
  • 请求/被错误地路由到我的 React 应用程序。

我如何才能landing.html响应请求/

the*_*ott 5

我最终打开了一个错误请求webpack-dev-middleware发现它不是错误而是配置失败。

具体来说,问题是HtmlWebpackPluginhistoryApiFallback. 我相信在正则表达式匹配之前处理插件,并且HtmlWebpackPlugin的默认文件输出是index.html; 这意味着开箱即用,/将始终路由到HtmlWebpackPlugin输出文件。

解决这个问题的方法是在 中设置一个自定义文件名HtmlWebpackPlugin,它允许您再次控制匹配。这是一个演示修复程序的示例 repo,这是 webpack 配置:

module.exports = {
  context: __dirname,
  entry: [
    './app.js',
  ],
  output: {
    path: __dirname + "/dist",
    filename: "bundle.js"
  },
  devServer: {
    publicPath: "/",
    // contentBase: "./public",
    // hot: true,
    historyApiFallback: {
      // disableDotRule: true,
      rewrites: [
        { from: /^\/$/, to: '/public/index.html' },
        { from: /^\/foo/, to: '/public/foo.html' },
        { from: /(.*)/, to: '/test.html' },
      ],
    }
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: "Html Webpack html",
      hash: true,
      filename: 'test.html',
      template: 'public/plugin.html',
    }),
  ],
};
Run Code Online (Sandbox Code Playgroud)