Completely 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 ofCommonJs
andAMD
, 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-levelthis
isundefined
(regular script iswindow
);The
var
declaration in the module will not be added to thewindow
object;##Es Module
is loaded and executed asynchronously;
- 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
importcommand is used to import the functions provided by other modules.
- 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
askeyword.
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 };
- 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复制代码
- After using the
- export
command to define the external interface of the module, other js files can be loaded through the
importcommand 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.
- 从上图可以看得出来,对象的属性被重新赋值了,而变量的则报了
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>
- 在浏览器中,引入相同的
nomodule
脚本会被执行多次,而模块只会被执行一次:
<script></script> <script></script> <script></script> <script></script> <script></script>
模块的默认延迟
- 默认情况下,
nomodule
脚本会阻塞HTML
解析。你可以通过添加defer
属性来解决此问题,该属性是等到HTML
解析完成之后才执行。
-
defer
andasync
are optional attributes, they can only choose one of them, under thenomodule
script,defer
The current script will not be parsed untilHTML
is parsed, andasync
will be parsed in parallel withHTML
and will not block the parsing ofHTML
, the module script can specify theasync
attribute, but it is invalid fordefer
, 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 theEs Module
andCommonjs
are completely different, they have three completely different types:
-
CommonJS
The module outputs a copy of the value,Es Module
The output is a reference to the value; -
CommonJS
module is loaded at runtime, andEs Module
is the compile-time output interface. -
CommonJS
Therequire()
of the module is to load the module synchronously, and theimport
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, themodule.exports
property), which is only available when the script is running It will be generated after completion. AndEs 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 fromCommonJS
.JS Engine
When statically analyzing a script, a read-only reference will be generated when the module loading commandimport
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 byimport
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:
-
Realm
: Create the scope of the current module; -
Environment
: Module The top-level binding environment record of Runtime property-based access. Module namespace objects have no constructor; -
HostDefined
: field is reserved for use by host environments - , additional information is required to associate with the module.
Module Environment Record
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.
- Before we start, let’s have a rough idea of what the entire process is like. Let’s have a general understanding:
Es Module parsing process
- Phase 1: Construction (
Construction
), find thejs
file according to the address, download it through the network, and parse the module file toModule Record
; - 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; - 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 inHTML
is usually a<script type="module"></script>
tag to represent a module file.
- The module continues to be declared through the
import
statement. There is a module declaration identifier in theimport
declaration statement. Character (ModuleSpecifier
), which tellsloader
how to find the address of the next module.
- Each module identification number corresponds to a
module record (Module Record)
, and eachmodule record
ContainsJavaScript code
,execution context
,ImportEntries
,LocalExportEntries
,IndirectExportEntries
,StarExportEntries
. TheImportEntries
value is aImportEntry Records
type, andLocalExportEntries
,IndirectExportEntries
,StarExportEntries
is aExportEntry Records
type.
ImportEntry Records
- A
ImportEntry Records
contains three fieldsModuleRequest
,ImportName
,LocalName
;
- ModuleRequest: a module identifier (
ModuleSpecifier
); - ImportName: generated by
ModuleRequest
The name of the required binding for the module export of the module identifier. The valuenamespace-object
indicates that the import request is for the namespace object of the target module; - LocalName: variable used to access the imported value from the current module from the imported module;
- For details, please refer to the figure below:
- The following table records the
ImportEntry Records
fields imported usingimport
Example:
Import Statement From | Module identifier(ModuleRequest) | Import name(ImportName) | LocalName | |
---|---|---|---|---|
"react" | "default" | "React" | ||
"react" | namespace -obj | "Moment" | ||
"react" | "useEffect" | "useEffect" | ||
"react" | "useEffect" | "effect" |
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 | "x" | |
"x" | null | null | "v" | ##export {x} from "mod"; |
"mod" | "x" | null | export {v as x} from "mod"; | |
"mod" | "v" | null | ##export * from "mod"; | |
"mod" | all-but-default | null | ##export * as ns from "mod"; | "ns |
all | 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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()".

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)".

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.

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.

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.

es2015 is es6. The full name of es is "ECMAScript", which is a universal scripting language implemented according to the ECMA-262 standard. The version officially released in June 2015 is officially called ECMAScript2015 (ES2015). Because it is the 6th version of ECMAScript, it can Referred to as es6.

The map is ordered. The map type in ES6 is an ordered list that stores many key-value pairs. The key names and corresponding values support all data types; the equivalence of key names is determined by calling the "Objext.is()" method. Implemented, so the number 5 and the string "5" will be judged as two types, and can appear in the program as two independent keys.
