现代模块依赖管理器原理

读完《你不知道的 JavaScript》上卷后,发现里面有个对模块依赖器原理的探究很值得记录。

原理是使用一个myModule变量接收一个立即执行函数通过闭包返回的函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let myModule = (function() {
var modules = {} // 模块保存的区域
function define(name, deps, impl) {
for (let i = 0; i < deps.length; i++) {
// 遍历依赖数组
deps[i] = modules[deps[i]] // 找到modules中保存的模块
}
modules[name] = impl.apply(impl, deps) // 正确追踪到依赖
}
function get(name) {
return modules[name]
}
return {
define,
get
}
})()

从而能通过暴露的 api 完成模块的定义和依赖引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
myModule.define('bar', [], function() {
function hello(who) {
return `let me introduce ${who}! `
}
return {
hello
}
})

myModule.define('foo', ['bar'], function(bar) {
let name = 'louis'
function awesome() {
console.log(bar.hello(name).toUpperCase())
}
return {
awesome
}
})

let bar = myModule.get('bar')
let foo = myModule.get('foo')

foo.awesome() // LET ME INTRODUCE LOUIS!