模块化
模拟模块化的实现
"use strict"
let module = (function () {
const moduleList = {}
function define(name, modules, action) {
modules.map((m, i) => {
modules[i] = moduleList[m]
})
moduleList[name] = action.apply(null, modules)
}
return { define }
})()
module.define('Tool', [], function () {
return {
first(arr) {
return arr[0]
},
max(arr, key) {
return arr.sort((a, b) => b[key] - a.key)[0]
}
}
})
module.define('lesson', ['Tool'], function (tool) {
let data = [
{ name: 'js', price: 199 },
{ name: 'mysql', price: 78 }
]
console.log(tool.max(data, 'price'))
})
模块化的基本语法
- 使用了模块的 JS 最后解析
- 模块默认是严格模式
- 模块有自己的独立作用域
- 模块是单例模式
具名导出
let title = '俊介历险记'
let url = 'https://www.alrcly.com'
export { title as titleA,url as urlA}
import { titleA as titleB, urlA as titleB } from './b.js'
批量导出
let title = '俊介历险记'
let url = 'https://www.alrcly.com'
export { title as titleA,url as urlA}
import * as pai from './b.js'
默认导出
let title = '俊介历险记'
let url = 'https://www.alrcly.com'
export default title
import title from './b.js'
混合导出
let title = '俊介历险记'
let url = 'https://www.alrcly.com'
export { url }
export default title
export {title as default ,url}
import titleA, { url } from './b.js'
按需动态导入
let title = '俊介历险记'
let url = 'https://www.alrcly.com'
export { title as titleA,url as urlA}
import('./b.js').then((title, url) => {
console.log(titie, url)
})