Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 38 ยท Code Splitting and Lazy Loading

Dynamic Imports and Lazy Loading

Master webpack dynamic import(): lazy-load routes and heavy features, name chunks with magic comments, use prefetch and preload, and handle loading errors.

Dynamic import() is the most useful code-splitting tool because it follows what your users actually do. You wrap a heavy feature in an import() call, and webpack moves the feature into its own chunk. The browser downloads that chunk only when the call runs: when a route opens, a button is clicked, or a dialog appears. This pattern is called lazy loading.

In this lesson you will see how the call works, how to name and group chunks with magic comments, how webpackPrefetch and webpackPreload warm the cache, and how to handle failures. It builds on Code Splitting.

Webpack is not runnable here. Config and source snippets are read-only. The TryIt blocks are Node.js stand-ins that reproduce the loader's behaviour (a promise cache, retries, prefetch ordering), and say so in comments.

How import() behaves

import('./module.js') returns a promise of the module namespace object. A named export foo is read as module.foo; the default export is module.default.

JavaScript
// src/router.js (read-only)
const routes = {
  '/': () => import('./pages/home.js'),
  '/reports': () => import('./pages/reports.js'),
  '/settings': () => import('./pages/settings.js'),
};

export async function navigate(path) {
  const page = await routes[path]();
  page.default.render(document.querySelector('#app'));
}

At build time webpack finds each import(), puts the target and its private dependencies into a chunk, and rewrites the call into something like __webpack_require__.e(chunkId).then(__webpack_require__.bind(__webpack_require__, moduleId)). The e function loads the chunk file (a <script> tag in browsers) and keeps a map from chunk id to promise, so a second request for the same chunk returns the same promise instead of fetching again.

A stand-in for the chunk loader

This stand-in imitates that cache. It counts "network" fetches so you can confirm that parallel and repeated requests share one download.

Node.js Stand-in: a chunk loader with a promise cache

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two concurrent requests produced a single download because both callers received the same promise. This is why you can safely call import() from several places.

Magic comments

You can steer webpack with comments inside the import() call.

JavaScript
const Chart = await import(
  /* webpackChunkName: "chart" */
  /* webpackPrefetch: true */
  './chart.js'
);
Comment Effect
webpackChunkName: "name" Names the output file (chart.js with a suitable chunkFilename). Imports with the same name share one chunk.
webpackPrefetch: true Adds <link rel="prefetch"> after the parent chunk loads; the browser downloads it when idle.
webpackPreload: true Adds <link rel="preload"> alongside the parent; loaded in parallel with it.
webpackMode: "lazy" Default: one chunk per import. lazy-once makes one chunk for all matches of a dynamic expression.
webpackInclude / webpackExclude Regex filters for dynamic expressions like import(./locale/${lang}.js).

Be careful: a typo in a magic comment is silently ignored in some setups, so check the output file names after changing them.

Prefetch versus preload

Prefetch means "you will probably need this later": it uses idle bandwidth at low priority. Preload means "you need this right now, but I am not part of the critical path": medium priority, requested together with the parent. A good rule: prefetch the next likely route, preload only something needed within a second of load. Misusing preload can delay the critical resources you meant to speed up.

The stand-in shows the practical effect: with prefetch, the click costs nothing because the chunk is already in the cache.

Node.js Stand-in: prefetch makes the click instant

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Lazy loading a React or Vue route

Frameworks wrap import() so a component renders a fallback while the chunk is on its way. In React that is React.lazy with Suspense; in Vue it is defineAsyncComponent or a route that returns () => import(...). Both rely on webpack for the chunking. See Webpack with React and Webpack with Vue and Svelte.

JSX
const Reports = React.lazy(() => import('./Reports'));

function App() {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <Reports />
    </Suspense>
  );
}

Handling failures

Network requests fail: the user goes offline, or a new deploy deleted the old chunk file you still reference. A rejected import() throws a ChunkLoadError. Production apps should catch it, retry a couple of times, and then ask the user to reload.

Node.js Stand-in: retry a failed chunk load

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Do not retry forever, and do not hide the problem: after the last attempt, show a message such as "A new version is available, please refresh".

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an import() call return?

    import() is asynchronous: it resolves to the module namespace, so you read named exports from it and the default export from .default.
  2. 2. What is the difference between webpackPrefetch and webpackPreload?

    Prefetch uses idle bandwidth for something needed later. Preload has higher priority and fetches alongside the parent chunk.
  3. 3. Why do two concurrent import('./a.js') calls cause only one download?

    The runtime keeps a map from chunk id to promise, so repeated or concurrent requests share one fetch.
  4. 4. Which is a sensible response to a ChunkLoadError in production?

    Transient network errors often succeed on retry, and a stale chunk after a deploy needs a reload. Infinite loops and silence both hurt users.

Summary

  • import() marks a split point and returns a promise of the module.
  • Magic comments name chunks and request prefetch or preload.
  • The runtime caches chunk promises, so a chunk downloads once.
  • Prefetch the likely next screen; preload sparingly.
  • Always plan for chunk load failures.

Next: The SplitChunksPlugin