Loading lesson path
import( module
);Dynamic Import is a way to load JavaScript modules at runtime, rather than at the start of your program.
Modern software splits imports into separate chunks.
Formula
Modules are downloaded only when requested - this method has many names:.Dynamic import is one of the most powerful features for modular and efficient code.
(which must appear at the top of a file),
Formula
Dynamic Import can be used anywhere - inside functions, conditionals, event handlers, etc.Syntax import("./module.js") The argument must be a string or expression that resolves to a path You must run the import inside a module script (<script type="module">)
Static import { add } from './math.js';Dynamic const math = await import('./math.js');Modules can improve performance by allowing tools to implement "code splitting". This means that a user's browser only needs to load the JavaScript modules required for the specific features they are using at a given moment, rather than the entire application's code at once. While modules themselves are a language feature, when combined with bundlers like Webpack or Rollup, they can lead to performance improvements through optimizations like tree-shaking (eliminating unused code), code splitting, and minification.
Example async function run() {
const module = await import("./math.js");
let result = module.add(2, 3);
}
run();math.js
// Export an "add" function export function add(a, b) {
return a + b;
}Inside run(), it dynamically loads math.js Once loaded, it gets access to the exported function add() It calls add(2, 3) and gets 5