Connecting the Dots
Presentation_不得不知道的事
前端模块化的发展
Press Space for next page
荒原
- 文件划分
// module-a.js
let data = 'data'
// module-b.js
function method() {
console.log('execute method')
}
- 命名冲突
- 作用域不明确
- 模块依赖加载
- 命名空间
// module-a.js
window.moduleA = {
data: 'moduleA',
method: function () {
console.log("execute A's method")
},
}
// module-b.js
window.moduleB = {
data: 'moduleB',
method: function () {
console.log("execute B's method")
},
}
- IIFE
// module-a.js
;(function () {
let data = 'moduleA'
function method() {
console.log(data + 'execute')
}
window.moduleA = {
method: method,
}
})()
争鸣
CommonJS(ServerJS)
- 模块化代码规范
- loader(自动加载模块)
- 第三方 loader(browserify)
- 同步模块请求
AMD
- Early Executing
define(['a', 'b', 'c', 'd', 'e', 'f'], function (a, b, c, d, e, f) {
// 所有模块都已经加载并执行
if (false) {
b.foo()
}
})
第三方 loader requireJS (原生不支持)
CMD & UMD
- Common Module Definition
@淘宝 SeaJS
前端模块化开发那点历史 · Issue #588 · seajs/seajs (github.com)
define(function (require, exports) {
var a = require('./a')
a.doSomething()
exports.foo = 'bar'
exports.doSomething = function () {}
})
- Universal Module Definition
兼容 AMD 和 CommonJS
万事皆允
ESM
// main.js
import { methodA } from './module-a.js'
methodA()
//module-a.js
const methodA = () => {
console.log('a')
}
export { methodA }
<body>
<div id="root"></div>
<script type="module" src="./main.js"></script>
</body>
@12.20
async function func() {
// 加载一个 ES 模块
const { a } = await import('./module-a.mjs')
console.log(a)
}
func()
module.exports = {
func,
}
基于 ESM 的 no-bundle 工具,模块加载交给浏览器