问题描述
因此,我有一个正在使用webpack-dev-server
运行的react webpack项目,一切正常,但是当url深度为两层并且刷新页面时,应用程序崩溃。
例如,如果我在http://localhost:8080/product/someProductId
或http://localhost:8080/checkout/information
刷新Failed to load resource: the server responded with a status of 404 (Not Found)
时收到此错误
但是如果它的http://localhost:8080/shop
不会在刷新时崩溃
这是我的webpack配置:
const path = require('path')
const HTMLPlugin = require('html-webpack-plugin')
const copyPlugin = require('copy-webpack-plugin');
module.exports ={
entry :"./src/index.js",devServer:{historyApiFallback: true},output:{
path:path.resolve(__dirname,"./dist"),filename:'index.js',},plugins:[
new HTMLPlugin({template:'./src/index.html'}),new copyPlugin({
patterns: [
{ from: './src/images',to: 'images' },],}),module:{
rules:[
{
test : /\.js$/,exclude:/node_modules/,use:{
loader:"babel-loader"
},{
test: /\.(png|gif|jpg)$/,include: [
path.join(__dirname,'./src/images')
],loader: 'file-loader',{
test:/.(png|jpg|woff|woff2|eot|ttf|svg|gif)$/,use: [
{
loader: 'url-loader',options: {
limit: 100000000,}
}
]
},{
test: /\.js$/,enforce: 'pre',use: ['source-map-loader'],{
test: /\.css$/i,loader: 'style-loader!css-loader'
},]
}
}
package.json的脚本:
"scripts": {
"nodemon": "nodemon ./backEnd/app.js","start": "webpack-dev-server --mode development --open --hot -inline --progress --content-base ","build": "webpack --mode production","watch": "webpack-dev-server --progress"
},
解决方法
告诉Webpack Dev Server将所有服务器请求重定向到/index.html
。您需要将Webpack配置中的两个属性设置为publicPath
和historyApiFallback
。
publicPath: '/',historyApiFallback: true,
publicPath
允许您为应用程序中的所有资产指定基本路径。 historyAPIFallback
将404重定向到/index.html。
这是一个例子:
module.exports = {
entry: './app/index.js',output: {
path: path.resolve(__dirname,'dist'),filename: 'index_bundle.js',publicPath: '/'
},devServer: {
historyApiFallback: true,}
// rest of your config ...
};
更多详细信息,请检查this