一、模块化简介
1、背景
脚本文件中的同名变量互相干扰。
2、模块化解决的问题
模块化主要解决 javascript 程序全局空间内被污染的问题
3、模块化规范
二、ES6 模块化规范
1、导出模块
创建”module”目录,创建 m1.js
1 2 3 4 5 6 7
| let star = '王力宏'
function sing() { console.log('大城小爱') }
export { star, sing }
|
创建 m2.js
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"> 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' 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 { username: 'helen', age: 20, coding() { console.log('hello world') }, }
|
2、导入模块
在 demo.html 中导入模块
1 2 3
| 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>
|