我正在用 webpack4 测试 react-router4,但我无法获得 webpack-dev-server 的设置:
{historyApiFallback: true}
工作。这在 webpack3 中使用得很好,所以我不确定哪里出了问题...这是我的 webpack.config.js:
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = () => {
return {
mode: 'development',
devtool: 'source-map',
devServer: {
port: 8888,
historyApiFallback: true,
stats: 'minimal'
},
resolve: {
extensions: ['*', '.mjs', '.js', '.jsx']
},
module: {
rules: [
{
test: /\.m?jsx?$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
title:'React Lab',
template: 'src/index.html'
})
]
}
}
这是我使用 react-router4 的简单 React 应用程序:
import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Route,
Link,
Switch
} from 'react-router-dom';
const mountNode = document.getElementById('app');
const App = () => (
<Router>
<div>
<ul>
<li><Link to="/">Link to: /</Link></li>
<li><Link to="/page1">Link to: /page1</Link></li>
<li><Link to="/page2">Link to: /page2</Link></li>
<li><Link to="/does/not/exist">Link to: /does/not/exist</Link></li>
</ul>
<button onClick={()=>{location.reload();}}>reload page</button>
<Switch>
<Route exact path="/" component={()=>(<h2>home</h2>)} />
<Route exact path="/page1" component={()=>(<h2>page1</h2>)} />
<Route exact path="/page2" component={()=>(<h2>page2</h2>)} />
<Route component={()=>(<h2>no match</h2>)} />
</Switch>
<Route path="/" component={(props) =><div>{`props.location.pathname: ${props.location.pathname}`}</div>} />
</div>
</Router>
);
ReactDOM.render( <App/>, mountNode
导航到之后:
<Link to="/does/not/exist" />
然后点击
<button>reload page</button>
webpack 开发服务器无法重定向到 main.js
完整代码在github: https://github.com/ApolloTang/webpack-dev-server-history-api-fall-back-not-working .
如有任何帮助或评论,我们将不胜感激。
最佳答案
原来我在webpack.config.js中缺少output.publicPath:
output: {
// must specified output.publicPath otherwise
// devServer.historyApiFallback will not work
publicPath: '/'
},
使用上面指定的 output.publicPath,historyApiFallback 工作。
我不记得我在哪里读到过 output.publicPath 在 webpack4 的配置中是可选的,但它确实需要与 webpack-dev-server 一起工作。
文档位于 https://webpack.js.org/configuration/output/#output-publicpath说:
The webpack-dev-server also takes a hint from publicPath, using it to determine where to serve the output files from.
但我不明白这与 historyApiFallback 有什么关系。
关于webpack-dev-server、historyApiFallback 不工作(webpack-4、react-router-4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53387756/