1. 程式人生 > 其它 >model.export和export default使用

model.export和export default使用

區別

  1. module.exports用於node模組塊開發,匯出某個模組,對應匯入require(‘xxx模組’) JavaScript 現在有兩種模組。一種是 ES6 模組,簡稱 ESM;另一種是 CommonJS 模組,簡稱 CJS。 CommonJS 模組是 Node.js 專用的,與 ES6 模組不相容 語法上面,兩者最明顯的差異是:

     

    • CommonJS 模組使用require()和module.exports,ES6 模組使用import和export
    • 它們採用不同的載入方案。從 Node.js v13.2 版本開始,Node.js 已經預設打開了 ES6 模組支援。
    • Node.js 要求 ES6 模組採用.mjs字尾檔名。也就是說,只要指令碼檔案裡面使用import或者export命令,那麼就必須採用.mjs字尾名。Node.js 遇到.mjs檔案,就認為它是 ES6 模組
  2. export default用於ES6中模組塊開發,匯出某個模組,對應匯入import XXX from 'xxx模組’

 

 

明確

module.exports與exports ,是CommonJS的規範,被使用於Node.js中。export與export default ,是ES6規範,被使用於React或Vue中。


注意:在node中使用原生的es語法進行匯入匯出,是作為實驗功能,不建議大家在正式的工程專案中使用

解析

Node使用CommonJS規範:

  定義每個模組的內部,module變數代表當前模組,exports是module的屬性,表示對外的介面。載入某個模組,實際上是載入該模組的module.exports屬性。


  Node為每隔模組提供了一個exports變數,指向module.exports,這等同於每個模組頭部有這樣的一行程式碼:

var exports = module.exports

  

ES6使用export和import來匯出/匯入模組。

1 export與export default均可用於匯出常量/函式/檔案/模組等;
2 在一個檔案或模組中,export/import可以有多個,export default只有一個;
3 通過export方式匯出,在匯入時需要加{},export default不需要;
4 export能匯出變數/表示式,export default不可以。
5 CommonJS模組輸出是一個值的拷貝,ES6模組輸出是值的引用。


6 CommonJS模組是執行時載入,ES6模組是編譯時輸出介面。
7 CommonJS模組無論require多少次,都只會在第一次載入時執行一次,然後儲存到快取中,下次在require,只會去從快取取。