Search code examples
webpacklazy-loadingcode-splitting

Webpack - Javascript not executed after code splitting


I am having a webpack configuration with a single entry point:

entry: {
    screengrid: './src/screengrid.js',
},

But I would like to have two bigger geo.json files excluded from the main js and loaded if required.

I am using this chunk code

 splitChunks: {
        cacheGroups: {
            map_1: {
                test: /world-low*\.geo/,
                name: 'maps/map_low',
                chunks: 'initial',
                priority: 20,
            },
            map_2: {
                test: /world-medium*\.geo/,
                name: 'maps/map_high',
                chunks: 'initial',
                priority: 20,
            },
            default: {
                reuseExistingChunk: true,
                priority: -50,
            },
        },
    },

Which does exactly what I want, in terms of file creation, but the script is not executing at all anymore. Not even a console.log on the first line.

Is this the right approach to lazy load files?

Thanks ralph


Solution

  • So found a few things:

    Split Chunks has nothing to do with lazy loading. All chunks must be referenced in the HTML. This is only good if you do not want to load all scripts on all pages.

    For lazy loading there is only the comment style solution

    **const _ = await import(/* webpackChunkName: "lodash" */ 'lodash');**
    

    See: https://webpack.js.org/guides/code-splitting/#dynamic-imports

    Or in my case, importing static files can be done with some fetch commands (or I am using d3.json).