所以我有一个使用WebPack devServer的React应用程序。如果我在localhost:8080/popular
并刷新页面,即使我在app.js
中指定当我们在/popular
路由时加载Popular
组件,我也会收到404错误:
class App extends React.Component {
render() {
return (
<Router>
<div className='container'>
<Nav />
<Switch>
<Route exact path='/' component={Home} />
<Route path='/popular' component={Popular} /> //RIGHT HERE
<Route render={function() {
return <p>Not found</p>
}} />
</Switch>
</div>
</Router>
)
}
}
尽管在网上进行了研究,但我很难理解为什么会这样。当我在historyApiFallback: true
下面添加publicPath: '/'
和webpack.config.js
时,它就起作用了:
let path = require('path');
let HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/' //Sets base path for our assets
},
module: {
rules: [
{
test: /\.(js)$/,
use: 'babel-loader'
},
{
test: /\.(css)$/,
use: ['style-loader', 'css-loader']
}
]
},
devServer: {
historyApiFallback: true
},
plugins: [new HtmlWebpackPlugin({
template: 'app/index.html'
})]
}
这是我的index.html
,当它由Webpack生成时:
<!DOCTYPE html>
<html en="lang">
<head>
<meta charset="utf-8"/>
<title>Github Battle</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="index_bundle.js"></script></body>
</html>
我的问题是,为什么webpack中的这两个属性使它工作,为什么在localhost:8080/
而不是localhost:8080/popular
上加载应用程序时它会起作用?