代码之家  ›  专栏  ›  技术社区  ›  Marvin

React router v4 broswer历史记录不使用代码拆分

  •  3
  • Marvin  · 技术社区  · 6 年前

    使用哈希历史记录时,代码拆分可与react router配合使用,但现在我即将投入生产,我想切换到浏览器历史记录。当我尝试更改路由时,会出现错误,例如,如果我尝试转到登录路由127.0.0.1:8080/身份验证/登录:

    拒绝从执行脚本 ' 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。OnScript完成(引导: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>
    

    历史js公司:

    import { createBrowserHistory } from 'history';
    
    export default createBrowserHistory({
        // add configurations here
    });
    

    网页包。dev.config。js

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

    *如果需要添加更多代码,请在注释中注明

    非常感谢。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Marvin    6 年前

    添加 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
        },
    }