Marvin
Marvin

Reputation: 485

React router v4 broswer history not working with code splitting

When using hash history code splitting works with react router but now i'm about to go into production and i want to switch to browser-history it gives an error when i try to change route, example if i try going to the login route 127.0.0.1:8080/auth/login :

Refused to execute script from 'http://127.0.0.1:8080/auth/3.bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

and

Uncaught (in promise) Error: Loading chunk 3 failed. (error: http://127.0.0.1:8080/auth/3.bundle.js) at HTMLScriptElement.onScriptComplete (bootstrap:108)

This is my router

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

Connect app:

 <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()
    ]
}

*If there is any more code to add please indicate in the comment

Thank you

Upvotes: 3

Views: 336

Answers (1)

Scott
Scott

Reputation: 3765

Add publicPath:"/" to the config:

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

Upvotes: 2

Related Questions