一、模块化简介

1、背景

脚本文件中的同名变量互相干扰。

2、模块化解决的问题

模块化主要解决 javascript 程序全局空间内被污染的问题

3、模块化规范

  • CommonJS 模块化规范(基于 ES6 语法之前)

    • 例如:node.js 中的 require 引入模块,exports 导出模块
  • ES6 模块化规范(使用 ES6 语法)

    • export 导出模块
    • import 引入模块

二、ES6 模块化规范

1、导出模块

创建”module”目录,创建 m1.js

1
2
3
4
5
6
7
let star = '王力宏'

function sing() {
console.log('大城小爱')
}

export { star, sing }

创建 m2.js

1
export let star = 5

2、导入模块

创建 demo.html

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script type="module">
// as起名/重命名
import * as m1 from './m1.js'
import * as m2 from './m2.js'

console.log(m1)
console.log(m2)

console.log(m1.star)
console.log(m2.star)

//还可以这样导入:解构赋值的形式
import { star, sing } from './m1.js'
import { star as star2 } from './m2.js' //使用as防止重名
console.log(star)
sing()
console.log(star2)
</script>
</body>
</html>

三、默认暴露模块

1、默认暴露

创建 m3.js

1
2
3
4
5
6
7
8
9
10
11
12
//可以导出任意类型,但同时只能有一个export default
// export default 'helen'
// export default 99

//大部分情况是导出对象
export default {
username: 'helen',
age: 20,
coding() {
console.log('hello world')
},
}

2、导入模块

在 demo.html 中导入模块

1
2
3
//导入m3
import m3 from './m3.js'
console.log(m3)

四、封装代码

1、创建 app.js

可以看做是程序的入口文件

1
2
3
4
5
6
7
import * as m1 from './m1.js'
import * as m2 from './m2.js'
import m3 from './m3.js'

console.log(m1)
console.log(m2)
console.log(m3)

2、引入入口文件

创建 demo-app.html

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>

<script src="app.js" type="module"></script>
</body>
</html>