模块的定义

模块是自动运行在严格模式下且没有办法退出运行的JS代码

模块与普通JS代码的区别在于可定义导入导出绑定

导出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 导出数据
export var color = "red"
export let name = "Nicholas"
export const magicNumber = 7

// 导出函数
export function sum (num1, num2) {
return num1 + num1
}

// 导出类
export class Rectangle {
constructor (length, width) {
this.Length = length
this.Width = width
}

// 未导出则为模块私有
function subtract (num1, num2) {
return num1 - num2
}

// 定义一个函数。...
function multiply (num1, num2) {
return num1 * num2
}

// 导出引用
export { multiply }

基本导入

1
import { a, b } from 'example.js'

整体导入

1
import * as example from 'example.js'

默认导入

1
import sum from 'example.js'