亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Previous review
天下狠CommonJs 久矣
動態(tài) import
使用頂層 await
import 的錯(cuò)誤使用
在瀏覽器中使用 Es Module
模塊的默認(rèn)延遲
The difference between Es Module and Commonjs
Related concepts of the working principle of Es Module
Module Record
import
Es Module parsing process
Construction construction phase
ImportEntry Records
ExportEntry Records
linking linking phase
Evaluation 求值階段
Es module 是如何解決循環(huán)引用的
Home Web Front-end JS Tutorial Completely understand es6 modularization in one article

Completely understand es6 modularization in one article

Feb 17, 2023 am 11:17 AM
es6

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只是一個(gè)值,不是一個(gè)接口export?1//?moment只是一個(gè)值為1的變量const?moment?=?1export?moment//?function和class的輸出,也必須遵守這樣的寫法function?foo(x,?y)?{????return?x+y
}export?foo復(fù)制代碼
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?'模塊標(biāo)識符'
    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

  • 從上圖可以看得出來,對象的屬性被重新賦值了,而變量的則報(bào)了 Assignment to constant variable 的類型錯(cuò)誤。
  • 如果模塊同時(shí)導(dǎo)出了命名導(dǎo)出和默認(rèn)導(dǎo)出,則可以在 import 語句中同時(shí)取得它們??梢砸来瘟谐鎏囟ǖ臉?biāo)識符來取得,也可以使用 * 來取得:
//?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";

動態(tài) import

  • 標(biāo)準(zhǔn)用法的 import 導(dǎo)入的模塊是靜態(tài)的,會使所有被導(dǎo)入的模塊,在加載時(shí)就被編譯(無法做到按需編譯,降低首頁加載速度)。有些場景中,你可能希望根據(jù)條件導(dǎo)入模塊或者按需導(dǎo)入模塊,這時(shí)你可以使用動態(tài)導(dǎo)入代替靜態(tài)導(dǎo)入。
  • 關(guān)鍵字 import 可以像調(diào)用函數(shù)一樣來動態(tài)的導(dǎo)入模塊。以這種方式調(diào)用,將返回一個(gè)?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});復(fù)制代碼

使用頂層 await

  • 在經(jīng)典腳本中使用 await 必須在帶有 async 的異步函數(shù)中使用,否則會報(bào)錯(cuò):
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 的錯(cuò)誤使用

  • 由于import是靜態(tài)執(zhí)行,所以不能使用表達(dá)式和變量,這些只有在運(yùn)行時(shí)才能得到結(jié)果的語法結(jié)構(gòu)。
//?錯(cuò)誤
import?{?'b'?+?'ar'?}?from?'./foo.js';

//?錯(cuò)誤
let?module?=?'./foo.js';
import?{?bar?}?from?module;

//?錯(cuò)誤
if?(x?===?1)?{
??import?{?bar?}?from?'./foo.js';
}?else?{
??import?{?foo?}?from?'./foo.js';
}

在瀏覽器中使用 Es Module

  • 在瀏覽器上,你可以通過將 type 屬性設(shè)置為 module 用來告知瀏覽器將 script 標(biāo)簽視為模塊。
<script></script><script></script>
  • 模塊默認(rèn)情況下是延遲的,因此你還可以使用 defer 的方式延遲你的 nomodule 腳本:
??<script>      
  console.log("模塊情況下的");
    </script>????
????<script></script>
????<script>
      console.log("正常 script標(biāo)簽");    
      </script>

Completely understand es6 modularization in one article

  • 在瀏覽器中,引入相同的 nomodule 腳本會被執(zhí)行多次,而模塊只會被執(zhí)行一次:
????<script></script>????<script></script>

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

Completely understand es6 modularization in one article

模塊的默認(rèn)延遲

  • 默認(rèn)情況下,nomodule 腳本會阻塞 HTML 解析。你可以通過添加 defer 屬性來解決此問題,該屬性是等到 HTML 解析完成之后才執(zhí)行。

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 導(dǎo)出的為父模塊,import 引入的為子模塊,父模塊可以對變量進(jìn)行修改,具有讀寫權(quán)限,而子模塊只有讀權(quán)限。

    Evaluation 求值階段

    • 在模塊彼此鏈接完之后,執(zhí)行對應(yīng)模塊文件中頂層作用域的代碼,確定鏈接階段中定義變量的值,放入內(nèi)存中。

    Es module 是如何解決循環(huán)引用的

    • Es Module 中有5種狀態(tài),分別為 unlinked、linking、linked、evaluatingevaluated,用循環(huán)模塊記錄(Cyclic Module Records)的 Status 字段來表示,正是通過這個(gè)字段來判斷模塊是否被執(zhí)行過,每個(gè)模塊只執(zhí)行一次。這也是為什么會使用 Module Map 來進(jìn)行全局緩存 Module Record 的原因了,如果一個(gè)模塊的狀態(tài)為 evaluated,那么下次執(zhí)行則會自動跳過,從而包裝一個(gè)模塊只會執(zhí)行一次。 Es Module 采用 深度優(yōu)先 的方法對模塊圖進(jìn)行遍歷,每個(gè)模塊只執(zhí)行一次,這也就避免了死循環(huán)的情況了。

    深度優(yōu)先搜索算法(英語:Depth-First-Search,DFS)是一種用于遍歷或搜索樹或圖的算法。這個(gè)算法會盡可能深地搜索樹的分支。當(dāng)節(jié)點(diǎn)v的所在邊都己被探尋過,搜索將回溯到發(fā)現(xiàn)節(jié)點(diǎn)v的那條邊的起始節(jié)點(diǎn)。這一過程一直進(jìn)行到已發(fā)現(xiàn)從源節(jié)點(diǎn)可達(dá)的所有節(jié)點(diǎn)為止。如果還存在未被發(fā)現(xiàn)的節(jié)點(diǎn),則選擇其中一個(gè)作為源節(jié)點(diǎn)并重復(fù)以上過程,整個(gè)進(jìn)程反復(fù)進(jìn)行直到所有節(jié)點(diǎn)都被訪問為止。

    Completely understand es6 modularization in one article

    • 看下面的例子,所有的模塊只會運(yùn)行一次:
    //?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 運(yùn)行 main.js ,得出以下結(jié)果:

    Completely understand es6 modularization in one article

    • 好了,這篇文章到這也就結(jié)束了?!?a href="http://ipnx.cn/course/list/17.html" target="_blank">JavaScript視頻教程》
    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 of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    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.

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Hot Topics

    PHP Tutorial
    1488
    72
    How to reverse an array in ES6 How to reverse an array in ES6 Oct 26, 2022 pm 06:19 PM

    In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

    Is async for es6 or es7? Is async for es6 or es7? Jan 29, 2023 pm 05:36 PM

    async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

    Why does the mini program need to convert es6 to es5? Why does the mini program need to convert es6 to es5? Nov 21, 2022 pm 06:15 PM

    For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

    How to find different items in two arrays in es6 How to find different items in two arrays in es6 Nov 01, 2022 pm 06:07 PM

    Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

    How to implement array deduplication in es5 and es6 How to implement array deduplication in es5 and es6 Jan 16, 2023 pm 05:09 PM

    In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

    What does es6 temporary Zenless Zone Zero mean? What does es6 temporary Zenless Zone Zero mean? Jan 03, 2023 pm 03:56 PM

    In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

    Is require an es6 syntax? Is require an es6 syntax? Oct 21, 2022 pm 04:09 PM

    No, require is the modular syntax of the CommonJS specification; and the modular syntax of the es6 specification is import. require is loaded at runtime, and import is loaded at compile time; require can be written anywhere in the code, import can only be written at the top of the file and cannot be used in conditional statements or function scopes; module attributes are introduced only when require is run. Therefore, the performance is relatively low. The properties of the module introduced during import compilation have slightly higher performance.

    How to determine how many items there are in an array in es6 How to determine how many items there are in an array in es6 Jan 18, 2023 pm 07:22 PM

    In ES6, you can use the length attribute of the array object to determine how many items there are in the array, that is, to get the number of elements in the array; this attribute can return the number of elements in the array, just use the "array.length" statement. Returns a value representing the number of elements of the array object, that is, the length value.

    See all articles