common.js和ES6的 模組的暴露與接收
阿新 • • 發佈:2019-01-11
commom.js:
module.exports是當前模組對外輸出的介面
a.js:
module.exports.fn=function(){...}
b.js:
var a=require('./a.js')
a.fn()
exports是module.exports的引用,單純的指向module.exports的記憶體中的值,即exports=module.exports={},故可以使用exports代替module.exports,但是不是很建議這樣做,使用module.exports更安全,出錯機率小。
ES6:
1.export可以選擇性地給其他模組暴露(提供)自己的屬性和方法,供其他模組使用。
a.js:
export var a='hello';
export function fn(){...}
//或者這樣寫:
var a='hello';
function fn(){...}
export {a,fn}
b.js:
import {a,fn} from './a.js';
console.log(a);
fn();
必須用{}包住變數名,並且匯入的變數名要和暴露的變數名一致。
2.export default 指預設暴露,一個檔案只能有一個:
a.js:
var a='hello'; function fn(){...} export default {a,fn}
b.js:
import msg from './a.js';
console.log(msg.a);
msg.fn();
不用{}包住,msg指項暴露的物件,msg可以任意取名字。
參考:傳送門 (非常詳細的介紹)