反应路由器v4 broswer历史记录无法使用代码拆分

时间:2018-05-04 21:55:59

标签: javascript reactjs webpack react-router-v4

当使用散列历史代码分割与反应路由器一起使用但现在我即将投入生产并且我想切换到浏览器历史记录时,当我尝试更改路由时会出现错误,例如,如果我尝试转到登录路线127.0.0.1:8080/auth/login:

  

拒绝执行脚本   'http://127.0.0.1:8080/auth/3.bundle.js'因为它的MIME类型   ('text / html')不可执行,严格的MIME类型检查是   启用。

  

未捕获(在承诺中)错误:加载块3失败。 (错误:   http://127.0.0.1:8080/auth/3.bundle.js)       在HTMLScriptElement.onScriptComplete(bootstrap:108)

这是我的路由器

<Router history={history}>
    <ConnectApp />
</Router>

连接应用:

 <Switch>
    {/* Front end */}
    <Route path="/" component={AsyncHome} exact />
    <Route path="/post/:id" component={AsyncPost} exact />

    {/* authentication */}
    <Route path="/auth/:section" component={AsyncLogin} exact />

    {/* Backend */}
    <PrivateRoute path="/admin/:path" component={AsyncAdmin} exact />
    <PrivateRoute
        path="/admin/edit-post/:id"
        component={AsyncEditPost}
        exact
    />

    <Route component={Err404} />
</Switch>

history.js:

import { createBrowserHistory } from 'history';

export default createBrowserHistory({
    // add configurations here
});

webpack.dev.config.js

module.exports = merge(common, {
    mode: 'development',
    devtool: 'inline-source-map',
    devServer: {
        contentBase: './dist',
        historyApiFallback: true
    }, 
    plugins: [
        new BundleAnalyzerPlugin()
    ]
}

*如果还有更多要添加的代码,请在评论

中注明

谢谢

1 个答案:

答案 0 :(得分:2)

publicPath:"/"添加到配置:

module.exports = merge(common, {
    mode: 'development',
    devtool: 'inline-source-map',
    devServer: {
        contentBase: './dist',
        historyApiFallback: true
    }, 
    plugins: [
        new BundleAnalyzerPlugin()
    ],

    output: {
        path: path.resolve('dist'),
        filename: '[name].bundle.js',
        chunkFilename: '[name].bundle.js',
        publicPath: '/' // Add this line
    },
}