Dynamic Imports

JavaScript Dynamic Imports (JavaScript动态导入)

Dynamic imports are slightly different from static imports. While static imports have a range of limits, dynamic ones are more flexible and multidimensional. For instance, static imports are limited to the top level of the file, can’t be loaded conditionally (inside if), and the name of the package might not be determined during execution. (动态导入与静态导入略有不同。虽然静态导入有一系列限制,但动态导入更加灵活和多维。例如,静态导入仅限于文件的顶层,无法有条件地加载(在if中) ,并且在执行过程中可能无法确定包的名称。)

Instead, all the actions above can be done with dynamic imports. (相反,上述所有操作都可以通过动态导入完成。)

Let’s start at the beginning. Export and import statements covered in the Chapter “Export and Import” are known as “static”. The syntax is quite strict and straightforward. (让我们从头开始。“进出口”一章中涵盖的进出口报表称为“静态”。语法非常严格和直截了当。)

But, still, it won’t allow you to generate any parameters of import dynamically. (但是,它仍然不允许您动态生成任何导入参数。)

The module path should be a primitive string and not a function call. Let’s consider an example that is not valid:

import...from getModuleName(); // Error, only from "string" is allowed

Conditional importing or importing at runtime is not possible either:

if (...) {
 import...; // Error, not allowed
}
{
 import...; // Error, we can't put imports in any block
}

The reason is that the aim of import/export is providing a backbone for the code structure. It is very convenient as the structure of the code can be analyzed, the modules can be grouped (bundled) into a single file by specific tools, the untouched exports can be deleted (“tree-shaken”). The simplicity of the export/import structure makes all that possible. (原因是导入/导出的目的是为代码结构提供骨干。由于可以分析代码的结构,因此非常方便,模块可以通过特定工具分组(捆绑)到单个文件中,可以删除未触及的导出( “树摇动” )。导出/导入结构的简单性使这一切成为可能。)

Now, we are going to explore the ways of importing a module dynamically, on-demand. (现在,我们将探索按需动态导入模块的方法。)

The Import() Expression

The Import() Expression (Import ()表达式)

The import(module) expression is aimed at loading the module and returning a promise, which returns into a module object that includes all its exports. You can call it from any place inside the code. (Import (module)表达式旨在加载模块并返回一个promise ,该promise返回到包含其所有导出的模块对象中。您可以从代码内的任何地方调用它。)

You can use it dynamically in any part of the code, as follows:

let module_Path = prompt("Which module to load?");
import (module_Path)
.then(obj => < module object > )
.catch(err => < loading error, if no such module > )

There is an alternative option, as well: using let module = await import(modulePath) inside an async function.

Let’s say you have the module welcome.js, like in the example below:

// welcome.js
export function welcome() {
 console.log(`Welcome`);
}
export function soon() {
 console.log(`See you soon`);
}

Now, you want to proceed with the dynamic import. (现在,您要继续动态导入。)

So, the example of the dynamic import will look like this:

let {
 welcome,
(欢迎)
 soon
} = await
import ('./welcome.js');
welcome();
soon();

It can also be used for the default export. So, if the welcome.js has the default export, its example will be as follows:

// welcome.js
export default function () {
 console.log("Module loaded (export default).");
}

The next step should be accessing it. For that purpose, you can use the default property of the module object, like this:

let obj = await
import ('./welcome.js');
let welcome = obj.default;
// or, in one line: let {default: welcome} = await import('./welcome.js');
say();

Please, take into consideration that dynamic imports operate within regular scripts and don’t require script type=“module”. (请考虑动态导入在常规脚本中运行,并且不需要script type = “module”。)

Although import() is similar to a function call, it is a specific syntax that happens to use parentheses ( like super()). Therefore, it’s not possible to copy import to variable or implement call/apply with it; it is not a function.

In brief, dynamic imports are handy in situations when you intend to load a module conditionally, either on-demand. The static ones are useful for loading initial dependencies and can benefit from readily from “tree shaking” and tools of static analysis. (简而言之,当您打算按需有条件地加载模块时,动态导入非常方便。静态依赖关系对于加载初始依赖关系非常有用,并且可以从“树摇动”和静态分析工具中轻松受益。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部