首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Node.js 模組匯入錯誤:TypeError: student.add is not a function 完整解析

     編輯:程式設計疑難解答

錯誤現場重現

開發者建立兩個簡單的 Node.js 檔案:

student.js

function add(student) {
  console.log(student);
}

exports.add = add;

teacher.js

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 無法正確解析模組匯出物件。

解決方案

  1. 統一檔案編碼為 UTF-8:在編輯器(VS Code、Sublime Text、WebStorm)中將兩個檔案儲存為 UTF-8 編碼
  2. 移除不必要的中文註解:刪除 //student.js、//teacher.js 以及分隔線註解
  3. 驗證模組匯出語法:確認 exports.add = add; 寫法正確

修正後的程式碼

student.js

function add(student) {
  console.log(student);
}

exports.add = add;

teacher.js

var student = require('./student');

function add(teacher) {
  console.log(teacher);
}

student.add('小明');
add('張老師');

最佳實踐建議

  • 專案統一使用 UTF-8 編碼,避免中文註解導致解析異常
  • 使用 .editorconfig 強制團隊編碼一致性
  • 模組匯出建議使用 module.exports = { add } 物件寫法,語意更清晰
  • 善用 ESLint 等靜態分析工具預先發現編碼問題

延伸知識:CommonJS 模組機制

Node.js 採用 CommonJS 規範,require 回傳的是 module.exports 物件。exports 只是 module.exports 的別名,重新賦值 exports = ... 會斷開連結,請務必使用 exports.xxx = ... 或 module.exports = ...。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved