CommonJS模块 输出值的拷贝,ES6模块 输出 值的引用
// a.js
let user = 'xxx'
const setUser = (val) => {
user = val
}
module.exports = { user, setUser}
// b.js
const { user, setUser } = require('./a.js')
console.log(user) // xxx
setUser('yyy')
console.log(user) // xxx
当前的 user 并没有改变
CommonJs的拷贝为浅拷贝
// a.js
let user = {
name: '?',
abilitys: {
say() {
console.log('hi')
},
play: 'js'
}
}
const changeAbility = (val) => {
user.abilitys = {...user.abilitys, ...val}
}
module.exports = { user, changeAbility}
// b.js
const { user, changeAbility } = require('./a.js')
console.log(user.abilitys.play) // js
changeAbility({ play: 'css' })
console.log(user.abilitys.play) // css
user.abilitys.play 更改为了 css
- CommonJS模块 运行时加载,ES6模块 编译时输出接口
- CommonJS模块 同步加载模块,ES6模块 异步加载