Back to Home

Dynamic imports

Export and import statements that we covered in previous chapters are called “static”. The syntax is very simple and strict. First, we can’t dynamically generate any parameters of import. The module path must be a primitive string, can’t be a function call. This won’t work: Second, we can’t import conditionally or at run-time: That’s because import/export aim to provide a backbone for the code structure. That’s a good thing, as code structure can be analyzed, modules can be gathered and bundled into one file by special tools, unused exports can be removed (“tree-shaken”). That’s possible only because the structure of imports/exports is simple and fixed. But how can we import a module dynamically, on-demand?

The import() expression

The import(module) expression loads the module and returns a promise that resolves into a module object that contains all its exports. It can be called from any place in the code. We can use it dynamically in any place of the code, for instance: Or, we could use let module = await import(modulePath) if inside an async function. For instance, if we have the following module say.js: …Then dynamic import can be like this: Or, if say.js has the default export: …Then, in order to access it, we can use default property of the module object: Here’s the full example: [codetabs src=“say” current=“index.html”]

import ... from *!*getModuleName()*/!*; // Error, only from "string" is allowed
Example:

Follow the lesson from Microsoft Web-Dev-For-Beginners course

Tags: web,development