Use of js Module module

1. What is Module

The design idea of ​​ES6 modules is to ensure 静态化that the module's dependencies, as well as input and output variables, can be determined at compile time. ES6 modules are not objects, but export命令code that explicitly specifies the output, and then passes import命令the input.

2. export command

1. A module is an independent file. All variables inside this file cannot be obtained from the outside. If you want the outside world to be able to read a variable inside the module, you must use export关键字the output variable.

example:

// profile.js
export var firstName = 'Michael';
export var lastName = 'Jackson';
export var year = 1958;

Explanation: The above code is the profile.js file, which saves user information. ES6 treats it as a module, which export命令exports three variables to the outside.

example:

// profile.js
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;

export {
    
     firstName, lastName, year };

Explanation: The above code is used after the export command to 大括号specify a set of variables to be output. It is equivalent to the previous way of writing (placed directly before the var statement), but this way of writing should be given priority. Because this way you can see at a glance which variables are output at the end of the script.

2. In addition to outputting variables, the export command can also output functions or classes. Normally, the variables output by export are their original names, but they can be as关键字renamed.

example:

function v1() {
    
     ... }
function v2() {
    
     ... }

export {
    
    
  v1 as streamV1,
  v2 as streamV2,
  v2 as streamLatestVersion
};

Explanation: The above code is used as关键字to rename the external interfaces of functions v1 and v2. After renaming, v2 can be output twice with different names.

3. The export command specifies the external interface and must establish a one-to-one correspondence with the variables inside the module.

example:

// 写法1:报错(直接输出 1)
export 1;

// 写法2:报错(通过变量m,还是直接输出 1。1只是一个值,不是接口。)
var m = 1;
export m;

// 写法3:正确
export var m = 1;

// 写法4:正确
var m = 1;
export {
    
    m};

// 写法5:正确
var n = 1;
export {
    
    n as m};

Explanation: The last three ways of writing are all correct. They specify the external interface m. Other scripts can get the value 1 through this interface. Their essence is to establish a one-to-one correspondence between and 接口名.模块内部变量

4. The interface output by the export statement is related to its corresponding value 动态绑定, that is, through this interface, the real-time value inside the module can be obtained.

example:

export var foo = 'bar';
setTimeout(() => foo = 'baz', 500);

Explanation: The above code outputs variable foo, whose value is bar, and changes to baz after 500 milliseconds.

5. export命令It can appear anywhere in the module, as long as it is at the top level of the module. If it is in block-level scope, an error will be reported.

example:

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

Explanation: In the above code, the export statement is placed in the function, and an error is reported.

3. import command

1. After using the export command to define the external interface of the module, other JS files can load this module through the import command.

example:

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

function setName(element) {
    
    
  element.textContent = firstName + ' ' + lastName;
}

Explanation: The import command of the above code is used to load the profile.js file and input variables from it. The import command accepts a pair of curly brackets, which specify the variable names to be imported from other modules. The variable name in the curly brackets must interface with the imported module (profile.js) 名称相同.

2. If you want to rename the input variable, use the import command as关键字to rename the input variable.

example:

import {
    
     lastName as surname } from './profile.js';

3. The variables entered by the import command are all variables 只读的, because its essence is the input interface. In other words, the interface is not allowed to be rewritten in the script that loads the module.

example:

import {
    
    a} from './xxx.js'

a = {
    
    }; // Syntax Error : 'a' is read-only;

Explanation: The script loads variable a, and an error will be reported if it is reassigned, because a is a read-only interface. However, if a is an object, overriding a's properties is allowed.

4. fromThe location of the specified module file after import can 相对路径be 绝对路径. If 不带有路径, is just a module name, then there must be 配置文件, telling JavaScript 引擎the location of the module.

example:

import {
    
     myMethod } from 'util';

Explanation: util is the name of the module file. Since it does not include a path, you must tell the engine how to get this module through configuration.

5. The import command has a promotion effect and will be promoted to the head of the entire module and executed first.

example:

foo();

import {
    
     foo } from 'my_module';

Explanation: The above code will not report an error because import is executed earlier than foo is called. The essence of this behavior is that the import command is executed during the compilation phase, before the code is run.

6. Since import is 静态执行, you cannot use 表达式and 变量, these syntax structures can only get the result at runtime.

example:

// 报错
import {
    
     'f' + 'oo' } from 'my_module';

// 报错
let module = 'my_module';
import {
    
     foo } from module;

// 报错
if (x === 1) {
    
    
  import {
    
     foo } from 'module1';
} else {
    
    
  import {
    
     foo } from 'module2';
}

Explanation: The above three writing methods will report errors because they use expressions, variables and if structures. During the static analysis stage, these syntaxes cannot be evaluated.

7. The import statement will execute the loaded module, so it can be written as follows.

example:

import 'lodash';

Explanation: The above code only executes the lodash module, but does not enter any value. If it is executed multiple times 同一句import语句, it will only be executed once, not multiple times.

4. Overall loading of modules

To specify a certain output value to load, you can also use overall loading, that is, specify 星号(*)an object, and all output values ​​will be loaded on this object.

Example: (load one by one)

import {
    
     area, circumference } from './circle';

console.log('圆面积:' + area(4));
console.log('圆周长:' + circumference(14));

Example: (whole load)

import * as circle from './circle';

console.log('圆面积:' + circle.area(4));
console.log('圆周长:' + circle.circumference(14));

Note: The object where the module is loaded as a whole (circle in the above example) should be statically analyzable, so it is not allowed to be changed at runtime.

5. export default command

1. In order to provide convenience to users and allow them to load the module without reading the documentation, the export default command is used to specify the default output for the module.

example:

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

Explanation: The import command in the above code can be used to 任意名称point to the output of export-default.js. In this case, there is no need to know the function name output by the original module. It should be noted that the following import command is not used at this time 大括号.

2. It is also possible to use the export default command 非匿名函数first .

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

// 或者写成

function foo() {
    
    
  console.log('foo');
}

export default foo;

Explanation: In the above code, the function name foo of the foo function is invalid outside the module. When loading, it is regarded as 匿名函数loading.

3. The export default command is used to specify the default output of the module. Obviously, a module can only have one default output, so the export default command can only be used once. Therefore, there is no need to add braces after the import command, because it can only uniquely correspond to the export default command.

example:

// 第一组
export default function crc32() {
    
     // 输出
  // ...
}

import crc32 from 'crc32'; // 输入

// 第二组
export function crc32() {
    
     // 输出
  // ...
};

import {
    
    crc32} from 'crc32'; // 输入

Explanation: The first group is when export default is used, the corresponding import statement does not need to use braces; the second group is when export default is not used, the corresponding import statement requires braces.

4. Export default is to output a defaultvariable or method called, and then the system allows you to give it any name. Therefore, the following writing is valid.

example:

// modules.js
function add(x, y) {
    
    
  return x * y;
}
export {
    
    add as default};
// 等同于
// export default add;

// app.js
import {
    
     default as foo } from 'modules';
// 等同于
// import foo from 'modules';

5. The export default command actually only outputs a variable called default, so it cannot be followed by a variable declaration statement.

// 正确
export var a = 1;

// 正确
var a = 1;
export default a;

// 错误
export default var a = 1;

Explanation: The meaning of export default a is to assign the value of variable a to variable default. Therefore, the last way of writing will report an error.

6. Compound writing of export and import

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

example:

export {
    
     foo, bar } from 'my_module';

// 可以简单理解为
import {
    
     foo, bar } from 'my_module';
export {
    
     foo, bar };

Explanation: In the above code, the export and import statements can be combined together and written in one line. But it should be noted that after writing it in one line, foo and bar are not actually imported into the current module, but are equivalent to 对外转发these two interfaces, resulting in the current module not being able to use foo and bar directly.

2. Module interface rename and overall output

example:

// 接口改名
export {
    
     foo as myFoo } from 'my_module';

// 默认接口输出
export {
    
     default } from 'my_module';

// 具名接口改为默认接口
export {
    
     es6 as default } from 'my_module';

// 整体输出
export * from 'my_module';

7. Cross-module constants

1. Constants declared as const are only valid in the current code block. If you want to set a cross-module constant (that is, across multiple files), or if a value is to be shared by multiple modules, you can use the following writing method.

example:

// constants.js 模块
export const A = 1;
export const B = 3;
export const C = 4;

// test1.js 模块
import * as constants from './constants';
console.log(constants.A); // 1
console.log(constants.B); // 3

// test2.js 模块
import {
    
    A, B} from './constants';
console.log(A); // 1
console.log(B); // 3

2. If there are a lot of constants to be used, you can create a special constants directory, write various constants in different files, and save them in this directory.

example:

Set constants by file:

// constants/db.js
export const db = {
    
    
  url: 'http://my.couchdbserver.local:5984',
  admin_username: 'admin',
  admin_password: 'admin password'
};

// constants/user.js
export const users = ['root', 'admin', 'staff', 'ceo', 'chief', 'moderator'];

Merged in index.js:

// constants/index.js
export {
    
    db} from './db';
export {
    
    users} from './users';

To load index.js directly use:

// script.js
import {
    
    db, users} from './constants/index';

Guess you like

Origin blog.csdn.net/change_any_time/article/details/128436924