0%

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<script>
///模块管理工具的开发

//需要有一个容器来管理模块,定义模块,往容器中添加模块,模块之间存在依赖,可以相互使用

let module =(function (){
const modulelist = {} //定义一个容器来存储模块
function define(name,modules,action) {
//依赖模块,m是依赖的具体模块,i是模块所在的索引号,
modules.map((m,i)=>{
modules[i]=modulelist[m];
// console.log(modulelist[m]);
// console.log(modules);

})

//执行并保存模块,保存的是它的结果
modulelist[name]=action.apply(null,modules)

}
return {define}
})()


//模块的名字,依赖其他模块,模块的功能
module.define('hd', [ ], function(){
return {
first(arr){
return arr[0];
},
max(arr,key ){
return arr.sort((a,b)=>{return b[key]-a[key]})[0];
}
};
})

module.define('lesson', ['hd'], function(hd){
console.log(hd);
let data = [
{name:'js', price: 199}, {name: 'mysql' ,price: 78}
]
console.log(hd.max(data,'price'));
});

</script>

模块的基本使用

导入模块时要把导入和导出的模块放在同一文件夹下,否则无法导出

模块具有独立的作用域

模块处于严格模式下

模块的预解析,只解析一次

模块的具名导入导出

模块的批量导出

1
import *as api from "./xxx.js"

导入导出的别名使用

模块的默认导出

1
2
3
export default class User{}
或者
export {User as default}

具名和默认导入导出的混合使用

1
import hd,{User} from "./xxx.js"
1
export {hd as default, User};

使用import函数按需动态加载模块

1
2
3
4
5
6
7
8
<script  type="module">
document.querySelector('button').addEventListener('click',()=>{
import("./test.js").then (({site,url})=>{
console.log(site, url);
})
})

</script>