Aug 1, 2017

Webpack, code-splitting, require & require.ensure()

Webpack allows for global definitions to be defined and set, allowing for compile time switches. This is especially useful when compiling a single source for multiple targets.

require() will include the target as a whole, while require.ensure() will create a code split point. Paired with the above concept of Webpack compile time switches, this allows us to define a code-splitted and and non-split version of our code.

An example:

In webpack.config.js:


plugins: [
    new webpack.DefinePlugin({
        BUILD_PDF: JSON.stringify(true),
    }),
]

In the target .js source:


if (BUILD_PDF) {
    require(....),
} else {
    require.ensure([], () =>{
        require(....);
    }, err => {
        // error code
    }, "split-name");
}

No comments:

Post a Comment

Thanks for contributing!! Try to keep on topic and please avoid flame wars!!