Webpack DevServer下BrowserRouter非根路由404 fallback失效
问题根因
- 自定义的
historyApiFallback规则未生效,核心原因有两点:- 最终导出的Webpack配置为数组格式(多配置导出模式),Webpack DevServer v4及以上版本要求
devServer配置必须挂载在导出的根对象层级,不能嵌套在数组内的单个打包配置项中。当前将devServer写在config_dist对象内部,WDS实际无法读取到自定义规则,控制台输出的“404s will fallback to /”是WDS的默认启动提示,并非应用自定义规则后的输出。 - 开发模式下Webpack DevServer将打包产物存储在内存中,不会实际写入磁盘的
dist目录。当前将静态资源服务路径contentBase指向了这个开发时没有实体文件的路径,historyApiFallback执行回退时无法读取到对应index.html文件,因此触发404。
- 最终导出的Webpack配置为数组格式(多配置导出模式),Webpack DevServer v4及以上版本要求
修正方案
无需配置代理即可实现BrowserRouter路由正常访问,调整点如下:
- 调整配置导出结构,将
devServer配置提取到导出对象的根层级,保证WDS可以正常读取 - 移除开发环境下无效的
contentBase指向,适配WDS v4+的static静态资源配置,指向开发时实际存在文件的源码目录 - 启用默认的historyApiFallback规则,覆盖所有非静态资源的404请求到
index.html
修正后的完整可用配置:
var path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const FileManagerPlugin = require("filemanager-webpack-plugin"); const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; const extractPlugin = { loader: MiniCssExtractPlugin.loader, }; module.exports = (env, argv) => { const IS_PRODUCTION = argv.mode === "production"; const baseConfig = { entry: [path.resolve(__dirname, "src", "index.js")], output: { path: path.resolve(__dirname, "dist"), filename: "nbviewer.js", publicPath: "/", }, module: { rules: [ { test: /\.(js)$/, exclude: /node_modules/, use: ["babel-loader"], }, { test: /\.s?[ac]ss$/, use: [extractPlugin, "css-loader", "sass-loader"], }, { test: /\.(eot|ttf|woff|woff2|svg|png|gif|jpe?g)$/, loader: require.resolve("url-loader"), }, ], }, plugins: [ new HtmlWebpackPlugin({ template: path.resolve(__dirname, "src", "index.html"), }), new MiniCssExtractPlugin({ filename: "index.css", }), new FileManagerPlugin({ onEnd: { copy: [ { source: path.resolve(__dirname, "static"), destination: path.resolve(__dirname, "dist"), }, ], }, }), ], node: { fs: "empty", }, mode: IS_PRODUCTION ? "production" : "development", devtool: "source-map", }; const devServerConfig = { port: 3000, historyApiFallback: true, static: { directory: path.join(__dirname, "public"), // 若不存在public目录可直接删除该配置 }, }; // 单配置导出,保证devServer可被WDS正常读取 return { ...baseConfig, devServer: devServerConfig, }; };
补充说明:WDS v4及以上版本中,原有contentBase配置已被static配置项替代,不再支持直接将值设置为磁盘路径的简写形式。
验证方式
重启DevServer后,直接在浏览器输入任意非根路径的前端路由地址,请求会自动回退到根路径加载index.html,由React Router在客户端完成路由匹配,不会再出现404报错。
内容的提问来源于stack exchange,提问作者danielfrg
相关产品推荐
相关产品推荐

