CommonJs/AMD导出
module.exports指向一个默认对象且不可更改。exports默认情况下指向module.exports,但指向可以更改。当module.exports和exports共存时,module.exports具有更高的优先级,会覆盖exports导出的变量
// file1
let fun = function(){
console.log('fun')
}
module.exports = {
fun: fun
}
// file2
const t2 = require('./t2.js')
console.log(t2) // { fun: [Function: fun] }
module.exports覆盖exports测试
/*
* 在测试代码添加如下代码,测试结果仍为{ fun: [Function: fun]}
*/
let test = function(){
console.log('exports func')
}
exports.test = test
ES6导出
使用 export/exprot default导出,importy引入非default变量使用{}
// file1
let hello = 'hello'
let fun1 = function(){
console.log('fun1')
}
function fun2(){
console.log('fun2')
}
export function fun3(){
console.log('fun3')
}
export default function defaultFunc(){
console.log('default func')
}
export {hello, fun1, fun2}
// file2
import defaultFunc, {hello, fun1, fun2, fun3} from './t2.js'
console.log(hello)
fun1()
fun2()
fun3()
defaultFunc()
/*
* hello
* fun1
* fun2
* fun3
* default func
*/