NodeJS--exports和module.exports

繼續遷移印象筆記中記錄相關筆記,其實工做中遇到的不少問題當時解決了,後期就忘記了,多記錄仍是頗有用的,好記性不如爛筆頭嘛,之後要養成好習慣。
NodeJS中 require 用來加載代碼,而 exports 和 module.exports 則用來導出代碼
module.exports使用示例:
let dbConfig = {
    user:"",
    password:"",
    port:27017,
    host:""
}

function test(){
    console.log('Hello, world!');
}

module.exports = {
   dbConfig:dbConfig,
   test:test
}

若是使用exports進行導出:
exports.dbConfig=dbConfig;

  

咱們只需知道三點就知道 exports 和 module.exports 的區別了:
  1. module.exports 初始值爲一個空對象 {}
  2. exports 是指向的 module.exports 的引用
  3. require() 返回的是 module.exports 而不是 exports
 
每個node.js執行文件,都自動建立一個module對象,同時,module對象會建立一個叫exports的屬性,初始化的值是 {}
 module.exports = {};
相關文章
相關標籤/搜索