tooling.report

feature

Dynamic import

Can split points be created using dynamic import?

Person in shorts with blue hair walking left

Introduction

In Code Splitting, a "split point" refers to an asynchronous module boundary that allows for a dependency to be bundled separately and loaded separately from the parent bundle. Creating split points makes it possible to control when the JavaScript for each part of an application is loaded, which is particularly useful for prioritising "first interaction" code over other scripts.

The most common syntax for denoting split points is Dynamic Import, the asynchronous version of an import statement.

The Test

This test checks to see if it's possible to create a split point using Dynamic Import.

index.js

(async function() {
  const { logCaps } = await import('./utils.js');
  logCaps('This is index');
})();

utils.js

export function logCaps(msg) {
  console.log(msg.toUpperCase());
}

The result should be two scripts: one for the index.js module, and another for utils.js. It should be possible to execute the first script before the second is loaded.

Conclusion

browserify

Browserify bundles CommnonJS code by statically analyzing synchronous require() calls to import modules. Since dynamic require usage and ECMAScript modules are both unsupported, neither can be used to create split points.

Issues

  • N/A
parcel

Parcel treats Dynamic Imports as code splitting boundaries, creating bundles for each.

rollup

Rollup treats Dynamic Imports as code splitting boundaries by default, creating bundles for each.

webpack

Webpack was one of the first bundlers to use Dynamic Imports as a signal for creating code-splitting boundaries.

Unlike multiple entries, split points created using Dynamic Imports consistently result in a separate bundle being created without customizing optimization.splitChunks.