4
Author: Dmitri Pavlutin
Translator: Front-end Xiaozhi Source: dmitripavlutin

If you have dreams and dry goods, you can search for [Great Move to the World] on WeChat and pay attention to this Shawanzhi who is still washing dishes in the early hours of the morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.

ECMAScript (aka ES2015 or ES) modules are a way to organize cohesive blocks of code in JavaScript.

The ES module system has 2 parts:

  • import module-use import { func } from './myModule'
  • export module-use export const func = () => {}

import Module is a module that imports dependencies using the import syntax:

 import { concat } from './concatModule';

concat('a', 'b'); // => 'ab'

And the imported module uses the export syntax to export components from itself:

 export const concat = (paramA, paramB) => paramA + paramB;

import { concat } from './concatModule' The way ES modules are used is static: it means the dependencies between modules are known at compile time.

While static imports are valid in most cases, sometimes we want to save bandwidth for our clients and load modules conditionally.

To achieve this, we can make a new dynamic import of a module using the import(pathToModule) syntax in a different way: as a function. Dynamic imports are a JavaScript language feature that started with ES2020 .

1. Importing dynamic modules

When the import keyword is used as a function instead of the static import syntax:

 const module = await import(pathToModule);

It returns a promise and starts an asynchronous task that loads the module. If the module is loaded successfully, then promise will resolve to the contents of the module, otherwise, promise will be rejected.

Note that pathToModule can be any expression whose value is a string representing the path to the imported module. Valid values are normal string literals (eg ./myModule ) or variables with strings.

For example, we load a module in an asynchronous function.

 async function loadMyModule() {
  const myModule = await import('./myModule');
  // ... use myModule
}

loadMyModule();

Interestingly, in contrast to static imports, dynamic imports accept expressions that are evaluated at the module path

 async function loadMyModule(pathToModule) {
  const myModule = await import(pathToModule);
  // ... use myModule
}

loadMyModule('./myModule');

Now that we understand how to load modules, let's see how to extract components from imported modules.

2. Import components

2.1 Import named components

Consider the following module:

 // namedConcat.js
export const concat = (paramA, paramB) => paramA + paramB;

Here a concat function is exported.

If you want to dynamically import namedConcat.js and access the named export concat , then just deconstruct it:

 async function loadMyModule() {
  const { concat } = await import('./namedConcat');
  concat('b', 'c'); // => 'bc'
}

loadMyModule();

2.2 Default export

If the module is exported by default, we can use the default attribute to access it.

Still in the above example, we export the defaultConcat.js concat function in ---df1f59ace26bd01d13a06e97143b536d--- by default:

 // defaultConcat.js
export default (paramA, paramB) => paramA + paramB;

In a dynamically imported module, you can use the default attribute to access:

 async function loadMyModule() {
  const { default: defaultImport } = await import('./defaultConcat');
  defaultImport('b', 'c'); // => 'bc'
}

loadMyModule();

Note that default is a keyword in JavaScript, so it cannot be used as a variable name.

2.3 Importing mixed forms

If there are both default exports and named exports in the module, they are also accessed by destructuring:

 async function loadMyModule() {
  const { 
    default: defaultImport,
    namedExport1,
    namedExport2
  } = await import('./mixedExportModule');
  // ...
}

loadMyModule();

3. When to use dynamic imports

It is recommended that dynamic import can be used for modules that are relatively large, or modules that need to be imported according to conditions.

 async function execBigModule(condition) {
  if (condition) {
    const { funcA } = await import('./bigModuleA');
    funcA();
  } else {
    const { funcB } = await import('./bigModuleB');
    funcB();
  }
}

execBigModule(true);

For small modules (such as namedConcat.js or defaultConcat.js in the previous example), there are only a few dozen lines of code, using dynamic import to kill chickens with a knife.

Summarize

When calling import(pathToModule) as a function whose parameter represents the specifier (aka path) of a module, the module is loaded dynamically.

In this case, module = await import(pathToModule) returns a promise that resolves to an object containing the components of the imported module.

Node.js (13.2 and above) and most modern browsers support dynamic imports.


The bugs that may exist in editing cannot be known in real time. In order to solve these bugs afterwards, a lot of time is spent on log debugging. By the way, here is a useful BUG monitoring tool , Fundebug .

Original: https://dmitripavlutin.com/ecmascript-modules-dynamic-import/

comminicate

The article is continuously updated every week, you can search for [Big Move to the World] on WeChat to read it as soon as possible, and reply to [Welfare] There are many front-end videos waiting for you. This article has been included on GitHub https://github.com/qq449245884/xiaozhi , welcome to Star .


王大冶
68.1k 声望105k 粉丝