问题:
使用BrowserRouter进行页面跳转后,再次刷新页面会显示404的错误或资源加载异常的情况。
原因:
使用browserHistory时,会创建真实的URL,处理初始/请求没有问题,但是对于跳转路由后,刷新页面或者直接访问该URL时,会发现无法正确响应。
解决:
-
默认情况下,没有修改output.publicPath值,只需要设置webpack-dev-server的historyApiFallback配置:
devServer: {
historyApiFallback: true
}
-
如果你在webpack配置文件中修改了 output.publicPath 值,那么你就需要声明请求重定向,配置historyApiFallback.index 值。
// output.publicPath: '/assets/'
historyApiFallback: {
index: '/assets/'
}
--------------------------------------------------分割线---------------------------------------------
新问题:
webpack-dev-server热更新没有问题,但是刷新页面后页面丢失报错!
GET http://localhost:8001/home/build.3f74f7aec8.js net::ERR_ABORTED 404 (Not Found)
Refused to apply style from 'http://localhost:8001/home/bundle.7b2511c3e5.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
解决方法:
webpack.config.js 添加 publicPath 属性
module.exports = {
output: {
path: path.resolve(__dirname, "build"),
filename: "build.[contenthash:10].js",
publicPath: "/",
},
}