1.JS模块管理
let module = (function () {
const moduleLists = {}
function define(name, modules, action) {
modules.forEach((name, index) => {
modules[index] = moduleLists[name]
})
moduleLists[name] = action.apply(null, modules)
}
return { define }
})()
module.define('zs', [], function () {
return {
show() {
console.log('zs的模块')
}
}
})
module.define('lisi', ['zs'], function (hd) {
hd.show()
})
2.模块的基本使用
2.1 模块文件使用export把需要导出的元素给导出。
2.2 使用文件需要使用import来接收想要使用的元素(不需要全部接收)。
3.3 script的type必须设置为module
let obj = {
name: '张三',
age: 18
}
function fun () {
console.log(obj.name)
}
export {fun}
<script type="module">
import {fun} from './test.js'
fun()
</script>
3.模块的特性
3.1 模块会在所有html,css,js文件解析完后才会解析
3.2 模块会在默认严格模式下进行
3.3 模块拥有私有的作用域,如果需要把私有的暴露出去就需要使用export()
4.使用别名导入
如果需要导出的变量名字太长可以使用as来给它起个别名。
let obj = {
data: {},
add () {
this.data = {name: '张三', age: 18}
},
show () {
return this.data
}
}
export {obj as zs}
<script type="module">
import {zs} from './module1.js'
console.log(zs)
</script>
5.默认导出
当只需要导出一个变量时就可以使用默认导出,这样在导入时就不需要加括号,而且可以随便起个名字
let obj = {
data: {},
add () {
this.data = {name: '张三', age: 18}
},
show () {
return this.data
}
}
export {obj as default}
<script type="module">
import myObj from './module1.js'
console.log(myObj)
</script>
6.模块的合并导出
就是做一个专门用来导入的JS文件,把需要导入的都收集起来,然后再统一导出,可以使用批量导出来解决命名冲突问题
import * as module1 from './module1.js'
import * as module2 from './module2.js'
export {module1, module2}
7.按需加载模块
使用then函数来执行,当成功加载了模块后就会自动调用then里面的,而且这种方法是不需要在文件开头就要使用的
document.querySelector('button').addEventListener('click', () => {
import('./module.js').then( module => {
console.log(module.module1.url)
})
})