Dynamic imports and code splitting with Vite
Dynamic imports in JavaScript refer to the usage of the import()
syntax to import a module. Unlike the import Something from './my-module.js'
declarative syntax, import()
is more akin to a function that returns a promise. For example, we could rewrite the original import as const Something =
await import('./my-module.js')
.
The “dynamic” part of the import is that it doesn’t have to be done at module evaluation time; it’s done as part of the execution of the code. This is useful when paired with code splitting – which we’ll define now – since it means that we can avoid loading and evaluating some JavaScript code until it’s needed.
Code splitting is a technique whereby code is built into multiple files (also known as “chunks” or “bundles”) instead of a single file. Code splitting is useful to avoid loading all the code up front. Instead...