跳到主要内容

模块化

一,模块化

1. export 导出

导出模块
// 导出name
export const name = 'square'
// 导出 name2
export const name2 = 'square'

// 默认导出
const fun1 = ()=>{
console.log('默认导出一个函数')
}

default export fun1

// 合并导出
export {name,name2}

2. import 导入

导入模块
// 导入多个模块
import { name } from './test.js'
// 导入在起别名
import { name as panws } from './test.js'
// 导入默认
import fun1 from './test.js'
在HTML中使用
<script type="module" src="main.js"></script>

3. 动态导入 import(url).then(module=>)

  • 动态导入将返回异步的 Promise 函数
动态导入
import('/modules/mymodule.js').then((module) => {
// Do something with the module.
})
// 实例,点击后在加载该模块
squareBtn.addEventListener('click', () => {
import('/js-examples/modules/dynamic-module-imports/modules/square.js').then(
(Module) => {
let square1 = new Module.Square(
myCanvas.ctx,
myCanvas.listId,
50,
50,
100,
'blue'
)
square1.draw()
square1.reportArea()
square1.reportPerimeter()
}
)
})
  • 请注意,由于 promise 履行会返回一个模块对象,因此该类成为对象的子特征,因此我们现在需要使用 Module 访问构造函数。
  • 在它之前,例如 Module.Square( ... )。

4. 创建模块对象

全部导入,进行使用
import * as Module from '/modules/module.js'
// 使用
Module.function1()
Module.function2()

5. 导出一个类,来使用

// 创建一个类
class Square {
constructor(ctx, listId, length, x, y, color) {
// …
}
draw() {
// …
}
// …
}
// 导出这个类
export { Square }
使用这个类
import { Square } from './modules/square.js'
let square1 = new Square(myCanvas.ctx, myCanvas.listId, 50, 50, 100, 'blue')
square1.draw()
square1.reportArea()
square1.reportPerimeter()

6. 合并模块

新建一个main.js文件,直接导入并重新导出即可
export { Square } from '/js-examples/modules/module-aggregation/modules/shapes/square.js'
export { Triangle } from '/js-examples/modules/module-aggregation/modules/shapes/triangle.js'
export { Circle } from '/js-examples/modules/module-aggregation/modules/shapes/circle.js'
使用合并后的模块
import { Square, Circle, Triangle } from './main.js'