Webpack - How to include chunk files in html?

Viewed 573

I build a react project, and run the production using express.

It is work, but on next step I using the optimization.splitChunks with webpack.

optimization: {
    runtimeChunk: 'single',
    splitChunks: {
        chunks: 'all',
        maxInitialRequests: Infinity,
        minSize: 0,
        cacheGroups: {
            vendor: {
                test: /[\\/]node_modules[\\/]/,
                name(module) {
                    // get the name. E.g. node_modules/packageName/not/this/part.js
                    // or node_modules/packageName
                    const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

                    // npm package names are URL-safe, but some servers don't like @ symbols
                    return `npm.${packageName.replace('@', '')}`;
                }
            }
        }
    }
}

Now I have multiple bundles. Such as main.cb042e4a129acc79cfb4.js, npm.axios.fa2892d5344ea2c206bf.js, etc.

So how do I edit this row in index.html now? how to include those file in index.html?

<script src="/dist/bundle.js"></script>
1 Answers

When your Webpack build spits out bundles/chunks with hashed ids - and you do not use tooling like for example the HtmlWebpackPlugin - you will need some kind of source => bundle mapping.

I use the WebpackManifestPlugin for this, but not with Express.

The gist is - on server startup you will have to read this manifest.json file and create something like <script src="{{vendorpath}}"></script> dynamically from the mappings in this file.

Related