Detailed explanation of ES6 Modules
Currently, almost all of our projects are developed based on build tools such as webpack and rollup, and modularization has become the norm.
We are no stranger to it. Today, we will systematically review the module mechanism of ES6 and summarize the common operations and best practices. We hope it will be helpful to you.
Some simple background
Take it as you go, it is a mechanism that we all hope to realize.
The same is true in Javascript. Divide a large Javascript program into different parts. Which part is to be used, just take that part.
[Related course recommendations: JavaScript video tutorial]
For a long time, NodeJS had such capabilities. Later, more and more libraries and frameworks It also has the ability to modularize, such as CommonJS, or implementation based on the AMD model (such as RequireJs), as well as subsequent Webpack, Babel, etc.
By 2015, a standard modular system was born. This is the protagonist we are going to talk about today - the ES6 model system.
At first glance, it is not difficult to find that the ES6 model system is very similar to the CommonJS syntax. After all, the ES6 model system comes from the CommonJS era and is deeply influenced by CommonJS.
Look at a simple example, such as in CommonJs: (https://flaviocopes.com/commonjs/)
//file.js module.exports = value; // 引入value const value = require('file.js')
And in ES6:
// const.js export const value = 'xxx'; import { value } from 'const.js'
The syntax is Very similar.
Below we will mainly look at import and export, and several related features to learn more about ES6 Modules.
The benefits of modularization
The main benefits of modularization are two points:
1. 避免全局变量污染 2. 有效的处理依赖关系
With the evolution of the times, Browsers have also begun to natively support es6 import and export syntax.
Let’s look at a simple example first:
<script> import { addTextToBody } from '/util.js'; addTextToBody('Modules are pretty cool.'); </script> // util.js export function addTextToBody(text) { const p = document.createElement('p'); p.textContent = text; document.body.appendChild(p); }
If you want to handle events, the same is true. Let’s look at a simple example:
<button>Show Message</button> <script></script> // showImport.js import { showMessage } from '/show.js' document.getElementById('test').onclick = function() { showMessage(); } // show.js export function showMessage() { alert("Hello World!") }
If you want to run this demo, be sure to set up a simple service:
$ http-server
Otherwise, you will see a CORS error.
As for the specific reasons for the error and other details, they are not the focus of this article. Those who are interested can read the following link for details.
https://jakearchibald.com/2017/es-modules-in-browsers/
strict mode
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
'use strict' statement is familiar to us, and we often use it in the es5 era, usually in The purpose of adding this statement at the top of the file is to disable the less friendly parts of Javascript and help us write more rigorous code.
This feature is enabled by default in es6 syntax. If there is less strict code in the code, an error will be reported, for example:
below I took some parts from MDN that are disabled
in strict mode
:
Variables can't be left undeclared
-
Function parameters
must haveunique names
(or are considered syntax errors) -
with
is forbidden - Errors are thrown on assignment to
read-only properties
-
Octal numbers
like 00840 aresyntax errors
- Attempts to
delete undeletable properties
throw an error -
delete prop
is a syntax error, instead of assuming delete global[prop] -
eval
doesn't introduce new variables into its surrounding scope -
eval
and arguments can't be bound or assigned to -
arguments
doesn't magically track changes to method parameters -
arguments.callee
throws a TypeError, no longer supported -
arguments.caller
throws a TypeError , no longer supported - Context passed as this in method invocations is not “boxed” (forced) into becoming an Object
- No longer able to use
fn.caller
and fn.arguments to access the JavaScript stack -
Reserved words
(e.g protected, static, interface, etc) cannot be bound
Several usages of exports
ES6 module only supports static export. You can only use export in the outermost scope of the module. It cannot be used in conditional statements or in functions. used in the domain.
In terms of classification, there are three main types of exports:
1. Named Exports (Zero or more exports per module)
2. Default Exports (One per module)
3. Hybrid Exports
Exports Overview:
// Exporting inpidual features export let name1, name2, …, nameN; // also var, const export let name1 = …, name2 = …, …, nameN; // also var, const export function functionName(){...} export class ClassName {...} // Export list export { name1, name2, …, nameN }; // Renaming exports export { variable1 as name1, variable2 as name2, …, nameN }; // Exporting destructured assignments with renaming export const { name1, name2: bar } = o; // Default exports export default expression; export default function (…) { … } // also class, function* export default function name1(…) { … } // also class, function* export { name1 as default, … }; // Aggregating modules export * from …; // does not set the default export export * as name1 from …; export { name1, name2, …, nameN } from …; export { import1 as name1, import2 as name2, …, nameN } from …; export { default } from …;
Now I will introduce the common usage of exports.
1. Named exports (导出每个函数/变量)
具名导出,这种方式导出多个函数,一般使用场景比如 utils、tools、common 之类的工具类函数集,或者全站统一变量等。
只需要在变量或函数前面加 export
关键字即可。
//------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); } //------ main.js 使用方式1 ------ import { square, diag } from 'lib'; console.log(square(11)); // 121 console.log(diag(4, 3)); // 5 //------ main.js 使用方式2 ------ import * as lib from 'lib'; console.log(lib.square(11)); // 121 console.log(lib.diag(4, 3)); // 5
我们也可以直接导出一个列表,例如上面的lib.js可以改写成:
//------ lib.js ------ const sqrt = Math.sqrt; function square(x) { return x * x; } function add (x, y) { return x + y; } export { sqrt, square, add }
2. Default exports (导出一个默认 函数/类)
这种方式比较简单,一般用于一个类文件,或者功能比较单一的函数文件使用。
一个模块中只能有一个export default默认输出。
export default与export的主要区别有两个:
不需要知道导出的具体变量名, 导入(import)时不需要{}.
//------ myFunc.js ------ export default function () {}; //------ main.js ------ import myFunc from 'myFunc'; myFunc();
导出一个类
//------ MyClass.js ------ class MyClass{} export default MyClass; //------ Main.js ------ import MyClass from 'MyClass';
注意这里默认导出不需要用{}。
3. Mixed exports (混合导出)
混合导出,也就是 上面第一点和第二点结合在一起的情况。比较常见的比如 Lodash,都是这种组合方式。
//------ lib.js ------ export var myVar = ...; export let myVar = ...; export const MY_CONST = ...; export function myFunc() { // ... } export function* myGeneratorFunc() { // ... } export default class MyClass { // ... } // ------ main.js ------ import MyClass, { myFunc } from 'lib';
再比如lodash例子:
//------ lodash.js ------ export default function (obj) { // ... }; export function each(obj, iterator, context) { // ... } export { each as forEach }; //------ main.js ------ import _, { forEach } from 'lodash';
4. Re-exporting (别名导出)
一般情况下,export输出的变量就是在原文件中定义的名字,但也可以用 as 关键字来指定别名,这样做一般是为了简化或者语义化export的函数名。
//------ lib.js ------ export function getUserName(){ // ... }; export function setName(){ // ... }; //输出别名,在import的时候可以同时使用原始函数名和别名 export { getName as get, //允许使用不同名字输出两次 getName as getNameV2, setName as set }
5. Module Redirects (中转模块导出)
有时候为了避免上层模块导入太多的模块,我们可能使用底层模块作为中转,直接导出另一个模块的内容如下:
//------ myFunc.js ------ export default function() {...}; //------ lib.js ------ export * from 'myFunc'; export function each() {...}; //------ main.js ------ import myFunc, { each } from 'lib'; export 只支持在最外层静态导出、只支持导出变量、函数、类,如下的几种用法都是错误的。 `错误`的export用法: //直接输出变量的值 export 'Mark'; // 未使用中括号 或 未加default // 当只有一个导出数,需加default,或者使用中括号 var name = 'Mark'; export name; //export不要输出块作用域内的变量 function () { var name = 'Mark'; export { name }; }
import的几种用法
import的用法和export是一一对应的,但是import支持静态导入和动态导入两种方式,动态import支持晚一些,兼容性要差一些。
下面我就总结下import的基本用法:
1. Import All things
当export有多个函数或变量时,如文中export的第一点,可以使用 * as 关键字来导出所有函数及变量,同时 as 后面跟着的名称做为 该模块的命名空间。
//导出lib的所有函数及变量 import * as lib from 'lib'; //以 lib 做为命名空间进行调用,类似于object的方式 console.log(lib.square(11)); // 121
2. Import a single/multiple export from a module
从模块文件中导入单个或多个函数,与 * as namepage 方式不同,这个是按需导入。如下例子:
//导入square和 diag 两个函数 import { square, diag } from 'lib'; // 只导入square 一个函数 import { square } from 'lib'; // 导入默认模块 import _ from 'lodash'; // 导入默认模块和单个函数,这样做主要是简化单个函数的调用 import _, { each } from 'lodash';
3. Rename multiple exports during import
和 export 一样,也可以用 as 关键字来设置别名,当import的两个类的名字一样时,可以使用 as 来重设导入模块的名字,也可以用as 来简化名称。
比如:
// 用 as 来 简化函数名称 import { reallyReallyLongModuleExportName as shortName, anotherLongModuleName as short } from '/modules/my-module.js'; // 避免重名 import { lib as UserLib} from "alib"; import { lib as GlobalLib } from "blib";
4. Import a module for its side effects only
有时候我们只想import一个模块进来,比如样式,或者一个类库。
// 导入样式 import './index.less'; // 导入类库 import 'lodash';
5. Dynamic Imports
静态import在首次加载时候会把全部模块资源都下载下来.
我们实际开发时候,有时候需要动态import(dynamic import)。
例如点击某个选项卡,才去加载某些新的模块:
// 当动态import时,返回的是一个promise import('lodash') .then((lodash) => { // Do something with lodash. }); // 上面这句实际等同于 const lodash = await import('lodash');
es7的新用法:
async function run() { const myModule = await import('./myModule.js'); const { export1, export2 } = await import('./myModule.js'); const [module1, module2, module3] = await Promise.all([ import('./module1.js'), import('./module2.js'), import('./module3.js'), ]); } run();
总结
以上, 我总结了ES6 Module 的简单背景和 常见的import , export 用法, 但这远远不是它的全部, 篇幅有限,如果想了解更多, 可以看下面的延伸阅读部分(质量都还不错, 可以看看)。
本文来自 js教程 栏目,欢迎学习!
The above is the detailed content of Detailed explanation of ES6 Modules. 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

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

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











How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
