ES6 must know (9) - Module

Module

1. At the level of language standards, ES6 implements the module function and becomes a common module solution for browsers and servers. It can completely replace CommonJS and AMD specifications. The basic features are as follows:

  • Each module is loaded only once, and each JS is executed only once. If the same file in the same directory is loaded next time, it will be read directly from the memory;
  • The variables declared in each module are local variables and will not pollute the global scope;
  • Variables or functions inside the module can be exported through export;
  • A module can import other modules

2. The module function is mainly composed of two commands: export and import. The export command is used to specify the external interface of the module, and the import command is used to input the functions provided by other modules;

3. A module is an independent file, and all the variables inside the file cannot be obtained externally. If you want the outside to be able to read a variable inside the module, you must use the export keyword to output the variable;

// profile.js
export var firstName = 'Michael';
export var lastName = 'Jackson'; export var year = 1958; //或者 // profile.js var firstName = 'Michael'; var lastName = 'Jackson'; var year = 1958; export {firstName, lastName, year}; 

4. The export command can output functions or classes in addition to output variables

export function multiply(x, y) { return x * y; }; 

Generally speaking, the variable output by export is the original name, but it can be renamed using the as keyword

function Module1() { ... }
function Module2() { ... } export { Module1 as Func1, Module2 as Func2 }; 

5. The interface output by the export statement, and its corresponding value is a dynamic binding relationship, that is, through this interface, the real-time value inside the module can be obtained;

export var str = 'hello';
setTimeout(() => str = 'world', 1000); console.log(str) 

The above code outputs the variable str with the value hello, which becomes world after 1 second.

6. The export command can appear anywhere in the module, as long as it is at the top level of the module. If it is in the block-level scope, it will report an error;

function foo() {
  export default 'bar' // SyntaxError } foo() 

7. After using the export command to define the external interface of the module, other JS files can load the module through the import command. The import command accepts a pair of curly brackets, which specify the variable names to be imported from other modules, and the variable names in the curly brackets , must be the same as the name of the external interface of the imported module (profile.js);

// main.js
import {firstName, lastName, year} from './profile';

function say() { console.log('Hello , ' + firstName + ' ' + lastName); } 

The import in the code above is used to load the profile.js file and import variables from it.

8. If you want to rename the input variable, you can also use the as keyword to rename the input variable.

import { lastName as secondName } from './profile';

9. The from after import specifies the location of the module file, which can be a relative path or an absolute path, and the .js suffix can be omitted. If it is just a module name without a path, then there must be a configuration file that tells the JavaScript engine where the module is located;

import { methods } from 'util';

10. The import command has a lifting effect and will be lifted to the head of the entire module, first executed

func();

import { func } from 'methods';

The above code will not throw an error because import is executed before func is called. Because the import command is executed in the compilation phase;

11. Since import is executed statically, expressions and variables cannot be used

// 报错
import { 'f' + 'oo' } from 'methods'; // 报错 let module = 'methods'; import { foo } from module; // 报错 if (x === 1) { import { foo } from 'module1'; } else { import { foo } from 'module2'; } 

The above three ways of writing will report an error, because they use expressions, variables and if structures. In the static analysis stage, these grammars cannot get the value;

12.import In addition to specifying to load an output value, you can also use overall loading, that is, specify an object with an asterisk (*), and all output values ​​are loaded on this object

// tools

export function circleArea(r){ return Math.PI * r * r ; } export function rectArea( w , h ){ return w * h ; } // main.js //逐一加载 import { circleArea , rectArea } from './tools'; console.log( '圆的面积是:' + circleArea( 5 ) ); console.log( '矩形的面积是:' + rectArea( 5 , 6 ) ); //整体加载 import * as area from './tools'; console.log( '圆的面积是:' + area.circleArea( 5 ) ); console.log( '矩形的面积是:' + area.rectArea( 5 , 6 ) ); 

Don't try to change the value of the object where the module is loaded as a whole (that is, the area in the above example) at runtime, it is not allowed;

13. The export default command specifies the default output for the module, so that when using the import command, you do not need to know the variable name or function name to be loaded;

// export-default.js
export default function () { console.log('foo'); } // import-default.js import customName from './export-default'; customName(); // 'foo' 

The above code is a module file export-default.js, and its default output is a function. When other modules load the module, the import command can specify any name for the anonymous function. In this case, no curly brackets are used after the import command;

14. It is also possible to use the export default command before a non-anonymous function.

// export-default.js
export default function foo() { console.log('hello world'); } // 或者写成 function foo() { console.log('hello world'); } export default foo; 

Note that a module can only have one default output, so the export default command can only be used once. Therefore, there is no need for curly brackets after the import command, because it can only correspond to one method; in fact, export default is to output a variable or method called default, and the system allows you to give it any name;

// modules.js
function add(x, y) { return x + y; } export { add as default }; // 等同于 // export default add; // app.js import { default as xxx } from 'modules'; // 等同于 // import xxx from 'modules'; 

15. Since the export default command actually only outputs a variable called default, it cannot be followed by a variable declaration statement;

// 正确
export var a = 1;

// 正确 var a = 1; export default a; //等同于将变量 a 的值赋给变量 default // 错误 export default var a = 1; 

16.export default can also be used to export classes.

// MyClass.js
export default class { ... } // main.js import MyClass from 'MyClass'; let o = new MyClass(); 

17. If in a module, the same module is input first and then output, the import statement can be written together with the export statement;

export { foo, bar } from 'module';

// 等同于
import { foo, bar } from 'module'; export { foo, bar }; 

18. The constant declared by const is only valid in the current code block. If you want to set constants across modules (that is, across multiple files), or if a value is to be shared by multiple modules, you can use the following writing method:

// constants.js 模块
export const A = 1;
export const B = 2; // test1.js 模块 import * as constants from './constants'; console.log(constants.A); // 1 console.log(constants.B); // 2 // test2.js 模块 import {A, B} from './constants'; console.log(A); // 1 console.log(B); // 2



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325990965&siteId=291194637