reactjs - 刷新时反应应用程序崩溃[webpack,REACT]
问题描述
所以我有这个反应 webpack 项目,我正在使用webpack-dev-server
一切正常运行,但是当 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 ...
};
更多细节检查这个
推荐阅读
- hugo - Hugo 页面内链接
- excel - 停止电源查询加载到 Excel 工作表
- apache-nifi - NiFi PutDatabaseRecord 处理器在 WHERE 子句中使用子查询进行更新
- scala - Scala Json 模式
- php - PHP 发送一个空的响应负载而不是 JSON
- python - 如何在一次函数调用中正确加密和解密句子?
- c# - 以编程方式设置 Visual Studio 项目调试属性
- javascript - 如何使用gridstack使动态创建的元素可拖动?
- javascript - auth0 Management Api NextJs 无法更新元数据
- python - 在 tkinter 中抖动边界