我正在使用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。
任何帮助或评论将不胜感激。
答案 0 :(得分:1)
事实证明,我在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上的文档说:
webpack-dev-server还会从publicPath中获取提示,并使用它来 确定从何处提供输出文件。
但是我不知道这与hisitoryApiFallback有什么关系。
答案 1 :(得分:0)
似乎您的output.publicPath
必须与devServer.historyApiFallback.index
匹配。
我想知道为什么没有自动暗示,除非另有说明,否则DevServer以相同的方式重用output.publicPath
。