CodePark/ questions / Modules
START PRACTICINGPRACTICE
Frontend question · JavaScript › Modules

What is dynamic import(), and how does it relate to code splitting and tree shaking?

import() loads a module while the code runs and returns a promise. Bundlers use it to split code into chunks. Tree shaking is a different optimization that removes unused exports.

Dynamic import(specifier):

  • It looks like a function call, but it is special syntax.
  • It returns a promise for the module's namespace object. This is one object that holds all of the module's exports as properties.
  • Unlike static import, you can use it anywhere, including inside conditions and event handlers.
  • The specifier (the module path) can be computed at runtime.
  • It works in both ES modules and CommonJS files.

Code splitting: bundlers treat each import() as a split point. The imported module and its dependencies go into a separate chunk (file). The browser downloads it only when that code runs. This is how lazy loading by route or feature works, for example React.lazy(() => import('./Chart')).

Tree shaking is the opposite kind of optimization. It removes exports that nothing imports. It relies on static import and export, which tools can analyze at build time.

So tree shaking works poorly with CommonJS. It also works poorly with modules that have side effects when imported.

  • import() returns a promise for the module's namespace object, which holds all its exports.
  • You can use import() anywhere, with a path computed at runtime.
  • Bundlers put each import() into a separate chunk, which enables lazy loading.
  • Tree shaking removes unused exports using static analysis at build time.
  • Modules with side effects and CommonJS limit tree shaking.