require、module exports模組設計
假設今天專案上有兩個JS檔案(app.js、data.js為B模組),要在 app.js 載入B模組下要如何操作?
Step1. 在 app.js 取得 B模組
當我們在 app.js 裡直接使用 data 時,如果還沒有載入B模組,Node.js 會跳出錯誤訊息:Uncaught ReferenceError ReferenceError:
data
is not defined
因此,想讓 app.js 使用B模組提供的內容,就需要依照Node.js的模組化規則,使用require()
將B模組載入。
var data = require('./data'); //載入模組

data.js成功載入B模組
Step2. B模組中匯出功能
此時 app.js 已經能「取得」B模組,但B模組內容尚未對外提供。所以使用module.exports語法 將變數或函式匯出。
// data.js
var message = '我是個訊息!!';
module.exports = message;

data.js 匯出,讓app.js取得訊息
進階使用
物件匯出,且物件中有變數與函式
app.js
var data = require('./data')
var a = 1;
console.log(a);
console.log(data);
console.log(data.msg);
console.log(data.say());
data.js
var message = "我是個訊息!!";
module.exports = {
msg: message,
title: "title",
say: function(){ return 'Say~'; }
};

進階使用物件傳送(資料有變數與函式)
exports 模組設計
exports 是一種語法糖。它本質是 module.exports
的簡寫。

exports語法糖
以下為exports與module.exports比較:
//data.js
exports.message = "我是個訊息!!"
exports.say = function(){ return 'Say~'; }
module.exports = {
message: '我是個訊息!!',
say:function(){ return 'Say'; }
};
注意事項
- 不能混用
- 如果同時使用, module.exports 會覆蓋 exports
- 若要寫入多個屬性 → 用
exports.xxx = …
就好 - 想直接輸出一整個物件→ 用
module.exports = { … }