search
HomeWeb Front-endJS TutorialCompletely understand es6 modularization in one article

Previous review

  • In the last article we talked about CommonJs. If you haven’t read it yet, you can find the column where this article is located to learn.
  • CommonJs has many excellent features, let’s briefly review them below:
  • Module code only runs after loading;

  • The module can only be loaded once;

  • The module can request to load other modules;

  • Supported Circular dependencies;

  • Modules can define public interfaces, and other modules can observe and interact based on this public interface;

天下狠CommonJs 久矣

  • Es Module is unique in that it can be loaded natively through the browser or with third-party loaders and build tools.
  • Browsers that support Es module modules can load the entire dependency graph from the top-level module, and it is done asynchronously. The browser will parse the entry module, determine the dependencies, and send a request for the dependent module. After these files are returned over the network, the browser will resolve their dependencies, and if these secondary dependencies have not been loaded, more requests will be sent.
  • This asynchronous recursive loading process will continue until the entire application's dependency graph has been resolved. After the dependency graph is parsed, the reference program can officially load the module.
  • Es Module not only borrows many excellent features of CommonJs and AMD, but also adds some new behaviors:
  • Es Module is executed in strict mode by default;

  • Es Module does not share the global namespace;

  • Es Module The value of the top-level this is undefined (regular script is window );

  • The var declaration in the module will not be added to the window object;

  • ##Es Module is loaded and executed asynchronously;

export and import

    The module function mainly consists of two commands:
  • exports and import. The
  • export command is used to specify the external interface of the module, and the import command is used to import the functions provided by other modules.
Basic use of export

    Basic form of export:
export const nickname = "moment";
export const address = "广州";
export const age = 18;
    Of course, you can also write it in the following form :
const nickname = "moment";
const address = "广州";
const age = 18;

export { nickname, address, age };
    Export an object and function to the outside world
export function foo(x, y) {
  return x + y;
}

export const obj = {
  nickname: "moment",
  address: "广州",
  age: 18,
};

// 也可以写成这样的方式
function foo(x, y) {
  return x + y;
}

const obj = {
  nickname: "moment",
  address: "广州",
  age: 18,
};

export { foo, obj };
    Normally, the variable output by
  • export is the original name, but can be renamed using the as keyword.
const address = "广州";
const age = 18;

export { nickname as name, address as where, age as old };
    Default export, it is worth noting that a module can only have one default export:
export default "foo";

export default { name: 'moment' }

export default function foo(x,y) {
  return x+y
}

export { bar, foo as default };
Incorrect use of export

    The export statement must be at the top level of the module and cannot be nested in a block:
if(true){
export {...};
}
  • export Must provide an external interface:
// 1只是一个值,不是一个接口export 1// moment只是一个值为1的变量const moment = 1export moment// function和class的输出,也必须遵守这样的写法function foo(x, y) {    return x+y
}export foo复制代码
Basic use of import

    After using the
  • export command to define the external interface of the module, other js files can be loaded through the import command The entire module
import {foo,age,nickname} from '模块标识符'
    The module identifier can be a relative path to the current module, an absolute path, or a pure string, but it cannot be the result of dynamic calculation, such as by virtue of String.
  • import The command accepts a curly bracket, which specifies the variable name to be imported from other modules, and the variable name must be the same as the name of the external interface of the imported module.
  • The imported variable cannot be reassigned because it is a read-only interface. If it is an object, the properties of the object can be reassigned. Exported modules can modify values, and imported variables will also change accordingly.

Completely understand es6 modularization in one article

  • 从上图可以看得出来,对象的属性被重新赋值了,而变量的则报了 Assignment to constant variable 的类型错误。
  • 如果模块同时导出了命名导出和默认导出,则可以在 import 语句中同时取得它们。可以依次列出特定的标识符来取得,也可以使用 * 来取得:
// foo.js
export default function foo(x, y) {
  return x + y;
}

export const bar = 777;

export const baz = "moment";

// main.js
import { default as foo, bar, baz } from "./foo.js";

import foo, { bar, baz } from "./foo.js";

import foo, * as FOO from "./foo.js";

动态 import

  • 标准用法的 import 导入的模块是静态的,会使所有被导入的模块,在加载时就被编译(无法做到按需编译,降低首页加载速度)。有些场景中,你可能希望根据条件导入模块或者按需导入模块,这时你可以使用动态导入代替静态导入。
  • 关键字 import 可以像调用函数一样来动态的导入模块。以这种方式调用,将返回一个 promise
import("./foo.js").then((module) => {  const { default: foo, bar, baz } = module;  console.log(foo); // [Function: foo]
  console.log(bar); // 777
  console.log(baz); // moment});复制代码

使用顶层 await

  • 在经典脚本中使用 await 必须在带有 async 的异步函数中使用,否则会报错:
import("./foo.js").then((module) => {
  const { default: foo, bar, baz } = module;
  console.log(foo); // [Function: foo]
  console.log(bar); // 777
  console.log(baz); // moment
});
  • 而在模块中,你可以直接使用 Top-level await:
const p = new Promise((resolve, reject) => {  resolve(777);
});const result = await p;console.log(result); 
// 777正常输出

import 的错误使用

  • 由于import是静态执行,所以不能使用表达式和变量,这些只有在运行时才能得到结果的语法结构。
// 错误
import { 'b' + 'ar' } from './foo.js';

// 错误
let module = './foo.js';
import { bar } from module;

// 错误
if (x === 1) {
  import { bar } from './foo.js';
} else {
  import { foo } from './foo.js';
}

在浏览器中使用 Es Module

  • 在浏览器上,你可以通过将 type 属性设置为 module 用来告知浏览器将 script 标签视为模块。
<script></script><script></script>
  • 模块默认情况下是延迟的,因此你还可以使用 defer 的方式延迟你的 nomodule 脚本:
  <script>      
  console.log("模块情况下的");
    </script>    
    <script></script>
    <script>
      console.log("正常 script标签");    
      </script>

Completely understand es6 modularization in one article

  • 在浏览器中,引入相同的 nomodule 脚本会被执行多次,而模块只会被执行一次:
    <script></script>    <script></script>

    <script></script>
    <script></script>
    <script></script>

Completely understand es6 modularization in one article

模块的默认延迟

  • 默认情况下,nomodule 脚本会阻塞 HTML 解析。你可以通过添加 defer 属性来解决此问题,该属性是等到 HTML 解析完成之后才执行。

Completely understand es6 modularization in one article

  • defer and async are optional attributes, they can only choose one of them, under the nomodule script, defer The current script will not be parsed until HTML is parsed, and async will be parsed in parallel with HTML and will not block the parsing of HTML , the module script can specify the async attribute, but it is invalid for defer, because the module is delayed by default.
  • For module scripts, if the async attribute is present, the module script and all its dependencies will be parsed and fetched in parallel, and the module script will be executed as soon as it is available.

The difference between Es Module and Commonjs

  • Before discussing the Es Module module, you must first understand the Es Module and Commonjs are completely different, they have three completely different types:
  1. CommonJS The module outputs a copy of the value, Es Module The output is a reference to the value;
  2. CommonJS module is loaded at runtime, and Es Module is the compile-time output interface.
  3. CommonJS The require() of the module is to load the module synchronously, and the import command of the ES6 module is to load asynchronously and has an independent module dependency analysis stage.
  • The second difference is because CommonJS loads an object (that is, the module.exports property), which is only available when the script is running It will be generated after completion. And Es Module is not an object. Its external interface is just a static definition, which will be generated during the static analysis phase of the code.
  • Commonjs What is output is a copy of the value. That is to say, once a value is output, changes within the module will not affect the value. For details, please see the previous article. The operating mechanism of
  • Es Module is different from CommonJS. JS Engine When statically analyzing a script, a read-only reference will be generated when the module loading command import is encountered. When the script is actually executed, the value will be retrieved from the loaded module based on this read-only reference. In other words, import is a connection pipe. If the original value changes, the value loaded by import will also change accordingly. Therefore, Es Module is a dynamic reference and does not cache values. The variables in the module are bound to the module in which they are located.

Related concepts of the working principle of Es Module

  • Before learning the working principle, we might as well understand the related concepts.

Module Record

  • Module Record (Module Record) encapsulates structural information about the import and export of a single module (the current module). This information is used to link the import and export of the connected module set. A module record consists of four fields, which are only used when executing the module. The four fields are:
  1. Realm: Create the scope of the current module;
  2. Environment: Module The top-level binding environment record of Runtime property-based access. Module namespace objects have no constructor;
  3. HostDefined: field is reserved for use by
  4. host environments
  5. , additional information is required to associate with the module. Module Environment Record
A module environment record is a declarative environment record used to represent the external scope of an ECMAScript module. In addition to the ordinary mutable and immutable bindings, module environment records also provide immutable

import

bindings that provide binding to a target that exists in another environment record indirect access.
  • Immutable binding means that the current module introduces other modules, and the introduced variables cannot be modified. This is the unique immutable binding of the module.
  • Es Module parsing process

    • Before we start, let’s have a rough idea of ​​what the entire process is like. Let’s have a general understanding:
  1. Phase 1: Construction (Construction), find the js file according to the address, download it through the network, and parse the module file to Module Record;
  2. Phase 2: Instantiation (Instantiation), instantiate the module, allocate memory space, parse the import and export statements of the module, and point the module to the corresponding memory address;
  3. Phase 3: Run (Evaluation), run the code, calculate the value, and fill the value into the memory address;

Construction construction phase

  • loader is responsible for addressing and downloading modules. First we modify an entry file, which in HTML is usually a <script type="module"></script> tag to represent a module file.

Completely understand es6 modularization in one article

  • The module continues to be declared through the import statement. There is a module declaration identifier in the import declaration statement. Character (ModuleSpecifier), which tells loader how to find the address of the next module.

Completely understand es6 modularization in one article

  • Each module identification number corresponds to a module record (Module Record), and each module record Contains JavaScript code, execution context, ImportEntries, LocalExportEntries, IndirectExportEntries, StarExportEntries . The ImportEntries value is a ImportEntry Records type, and LocalExportEntries, IndirectExportEntries, StarExportEntries is a ExportEntry Records type.

ImportEntry Records

  • A ImportEntry Records contains three fields ModuleRequest, ImportName,LocalName;
  1. ModuleRequest: a module identifier (ModuleSpecifier);
  2. ImportName: generated by ModuleRequest The name of the required binding for the module export of the module identifier. The value namespace-object indicates that the import request is for the namespace object of the target module;
  3. LocalName: variable used to access the imported value from the current module from the imported module;
  • For details, please refer to the figure below:Completely understand es6 modularization in one article
  • The following table records the ImportEntry Records fields imported using import Example:
##import React from "react";"react""default""React"import * as Moment from "react";"react"namespace -obj"Moment"import {useEffect} from "react";"react""useEffect" "useEffect"##import {useEffect as effect } from "react";

ExportEntry Records

  • A ExportEntry Records contains four fields ExportName, ModuleRequest, ImportName , LocalName, and ImportEntry Records are different in that there is an additional ExportName.
  1. ExportName: The name this module uses to bind when exporting.
  • The following table records examples of ExportEntry Records fields exported using export:

Import Statement From Module identifier(ModuleRequest) Import name(ImportName) LocalName
"react" "useEffect" "effect"
##export {x};"x"nullnull "x"##export {v as x};##export {x} from "mod";"x""mod""x"nullexport {v as x} from "mod";"x""mod""v"nullnull##export * as ns from "mod";"ns"mod"allnull
  • Back to topic

  • Only after parsing the current Module Record can we know which submodules the current module depends on , then you need to resolve the submodule, obtain the submodule, then parse the submodule, and continuously cycle this process resolving -> fetching -> parsing. The result is as shown in the figure below:

  • Completely understand es6 modularization in one article

    • This process is also called static analysis. It will not run JavaScript code and will only identify export and import keyword, so import cannot be used in non-global scope, except for dynamic import.
    • What if multiple files depend on one file at the same time? Will this cause an infinite loop? The answer is no.
    • loader Use Module Map to track and cache the global MOdule Record to ensure that the module is only fetch Once, there will be an independent Module Map in each global scope.

    MOdule Map is a key/value mapping object composed of a URL record and a string. The URL record is the request URL to get the module, a string indicating the type of module (e.g. "javascript"). The value of the module map is either the module script, null (used to indicate a failed fetch), or the placeholder value "fetching".

    Completely understand es6 modularization in one article

    linking linking phase

    • After all Module Record are parsed, the next JS engine needs Link all modules. The JS engine takes the Module Record of the entry file as the starting point, recursively links the modules in depth-first order, and creates a Module Environment Record for each Module Record. Used to manage variables in Module Record.

    Completely understand es6 modularization in one article

    • ##Module Environment Record has a Binding, which is used to store Module The variables exported by Record, as shown in the figure above, export a variable of count at the module main.js, in Module Environment Record The Binding will have a count. At this time, it is equivalent to the compilation phase of V8, creating a module instance object, adding the corresponding attributes and Method, the value at this time is undefined or null, allocate memory space for it.
    • The
    • import keyword is used in the submodule count.js to import main.js, and count. The import of js and the export variable of main.js point to the same memory location, thus linking the relationship between the parent and child modules. Woke up. As shown below:

    Completely understand es6 modularization in one article

    • 需要注意的是,我们称 export 导出的为父模块,import 引入的为子模块,父模块可以对变量进行修改,具有读写权限,而子模块只有读权限。

    Evaluation 求值阶段

    • 在模块彼此链接完之后,执行对应模块文件中顶层作用域的代码,确定链接阶段中定义变量的值,放入内存中。

    Es module 是如何解决循环引用的

    • Es Module 中有5种状态,分别为 unlinkedlinkinglinkedevaluatingevaluated,用循环模块记录(Cyclic Module Records)的 Status 字段来表示,正是通过这个字段来判断模块是否被执行过,每个模块只执行一次。这也是为什么会使用 Module Map 来进行全局缓存 Module Record 的原因了,如果一个模块的状态为 evaluated,那么下次执行则会自动跳过,从而包装一个模块只会执行一次。 Es Module 采用 深度优先 的方法对模块图进行遍历,每个模块只执行一次,这也就避免了死循环的情况了。

    深度优先搜索算法(英语:Depth-First-Search,DFS)是一种用于遍历或搜索树或图的算法。这个算法会尽可能深地搜索树的分支。当节点v的所在边都己被探寻过,搜索将回溯到发现节点v的那条边的起始节点。这一过程一直进行到已发现从源节点可达的所有节点为止。如果还存在未被发现的节点,则选择其中一个作为源节点并重复以上过程,整个进程反复进行直到所有节点都被访问为止。

    Completely understand es6 modularization in one article

    • 看下面的例子,所有的模块只会运行一次:
    // main.js
    import { bar } from "./bar.js";
    export const main = "main";
    console.log("main");
    
    // foo.js
    import { main } from "./main.js";
    export const foo = "foo";
    console.log("foo");
    
    // bar.js
    import { foo } from "./foo.js";
    export const bar = "bar";
    console.log("bar");
    • 通过 node 运行 main.js ,得出以下结果:

    Completely understand es6 modularization in one article

    Export declaration Export name Module identifier Import name Local name
    export var v; "v" null null "v"
    export default function f() {} "default" null null "f"
    export default function () {} "default" null null "default"
    export default 42; "default" null null "default"
    "x" null null "v"
    ##export * from "mod";
    "mod" all-but-default null

    The above is the detailed content of Completely understand es6 modularization in one article. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
    es6怎么判断是否为数组es6怎么判断是否为数组Apr 25, 2022 pm 06:43 PM

    在es6中,可以利用“Array.isArray()”方法判断对象是否为数组,若判断的对象是数组,返回的结果是true,若判断对象不是数组,返回的结果是false,语法为“Array.isArray(需要检测的js对象)”。

    es6中遍历跟迭代的区别是什么es6中遍历跟迭代的区别是什么Apr 26, 2022 pm 02:57 PM

    es6中遍历跟迭代的区别是:遍历强调的是要把整个数据依次全部取出来,是访问数据结构的所有元素;而迭代虽然也是依次取出数据,但是并不保证取多少,也不保证把所有的数据取完,是遍历的一种形式。

    es6中怎么判断两个对象是否相等es6中怎么判断两个对象是否相等Apr 19, 2022 pm 03:34 PM

    在es6中,可用Object对象的is()方法来判断两个对象是否相等,该方法检测两个变量的值是否为同一个值,判断两个对象的引用地址是否一致,语法“Object.is(对象1,对象2)”;该方法会返回布尔值,若返回true则表示两个对象相等。

    es6怎么将数字转为字符串es6怎么将数字转为字符串Apr 19, 2022 pm 06:38 PM

    转换方法:1、利用“+”给数字拼接一个空字符,语法“数字+""”;2、使用String(),可把对象的值转换为字符串,语法“String(数字对象)”;3、用toString(),可返回数字的字符串表示,语法“数字.toString()”。

    es6中assign的用法是什么es6中assign的用法是什么May 05, 2022 pm 02:25 PM

    在es6中,assign用于对象的合并,可以将源对象的所有可枚举属性复制到目标对象;若目标对象与源对象有同名属性,或多个源对象有同名属性,则后面的属性会覆盖前面的属性,语法为“Object.assign(...)”

    es6怎么改变数组数据es6怎么改变数组数据Apr 26, 2022 am 10:08 AM

    改变方法:1、利用splice()方法修改,该方法可以直接修改原数组的内容,语法为“数组.splice(开始位置,修改个数,修改后的值)”;2、利用下标访问数组元素,并重新赋值来修改数组数据,语法为“数组[下标值]=修改后的值;”。

    sort排序是es6中的吗sort排序是es6中的吗Apr 25, 2022 pm 03:30 PM

    sort排序是es6中的;sort排序是es6中用于对数组的元素进行排序的方法,该方法默认不传参,按照字符编码顺序进行排序,排序顺序可以是字母或数字,并按升序或降序,语法为“array.sort(callback(a,b))”。

    import as在es6中的用法是什么import as在es6中的用法是什么Apr 25, 2022 pm 05:19 PM

    在es6中,import as用于将若干export导出的内容组合成一个对象返回;ES6的模块化分为导出与导入两个模块,该方法能够将所有的导出内容包裹到指定对象中,语法为“import * as 对象 from ...”。

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!