開發者建立兩個簡單的 Node.js 檔案:
function add(student) {
console.log(student);
}
exports.add = add;
var student = require('./student');
function add(teacher) {
console.log(teacher);
}
student.add('小明');
add('張老師');
TypeError: student.add is not a function
at Object. (teacher.js:9:9)
...
這不是程式邏輯錯誤,而是檔案編碼問題。原始碼中的中文註解導致檔案編碼不一致,Node.js 無法正確解析模組匯出物件。
//student.js、//teacher.js 以及分隔線註解exports.add = add; 寫法正確function add(student) {
console.log(student);
}
exports.add = add;
var student = require('./student');
function add(teacher) {
console.log(teacher);
}
student.add('小明');
add('張老師');
.editorconfig 強制團隊編碼一致性module.exports = { add } 物件寫法,語意更清晰Node.js 採用 CommonJS 規範,require 回傳的是 module.exports 物件。exports 只是 module.exports 的別名,重新賦值 exports = ... 會斷開連結,請務必使用 exports.xxx = ... 或 module.exports = ...。