Search code examples
webpackreact-router-v4react-loadable

React loadable splitted files are using wrong path with react router


I just tried to add react-loadable to my project, and it works fine until I access my admin pages. I currently have webpack 4, react-router 4.2.2 and react-loadable 5.4.0. I have something like this in my approuter:

<Route path="/admin/users" component={LoadableUsers} />

And LoadableUser:

const LoadableUsers = Loadable({
    loader: () => import('../admin/components/user/Users'),
    loading: Loading,
})

Accessing localhost:3000/admin/users gives me the following:

Refused to execute script from 'http://localhost:3000/admin/4.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

Because the 4.js (splitted file by react-loadable) is not located under /admin, but directly under root.

Any ideas? It feels like a react-router or webpack issue...

My webpack config:

module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.html$/,
                use: [
                    {
                        loader: "html-loader",
                        options: {minimize: true}
                    }
                ]
            },
            {
                test: /\.s?css$/,
                use: [
                    devMode ? 'style-loader' : 'style-loader',
                    "css-loader",
                    {
                        loader: "sass-loader", options: {
                            sourceMap: true
                        }
                    }
                ]
            },
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: "[path][name].[hash].[ext]",
                        }
                    }
                ]
            }]
    },
    plugins: [
        new HtmlWebPackPlugin({
            inject: false,
            template: "./public/index.html",
            filename: "./index.html"
        }),
        new MiniCssExtractPlugin({
            filename: devMode ? '[name].css' : '[name].[hash].css',
            chunkFilename: devMode ? '[id].css' : '[id].[hash].css',
        }),
    ],
    devtool: devMode ? 'cheap-module-eval-source-map' : 'source-map',
    devServer: {
        contentBase: path.join(__dirname, 'public'),
        historyApiFallback: true,
    },

Solution

  • Added output and entry in order to make it properly work:

    entry: ['babel-polyfill', './src/index.js'],
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
        chunkFilename: '[name].chunk.js',
        publicPath: '/'
    },