require 引入模块, require 引入模块, require 引入模块,
Node.js 词条目录
前端Wiki/Node.js/基础/模块系统与全局对象

CommonJS:require 与 module.exports

Node.js 默认使用 CommonJS 模块规范:require 引入模块,module.exports 导出接口。每个 .js 文件天然是一个独立模块,拥有自己的作用域,变量不会泄漏到全局。

最常见的坑:exports 是 module.exports 的别名(指向同一对象),但一旦给 exports 重新赋值,两者就断开连接。最终被 require 拿到的永远是 module.exports。

  • require(路径):文件模块以 ./ 或 ../ 开头,核心模块直接写名字(fs、path)
  • module.exports 是真正的导出对象;exports 只是它的快捷引用
  • 模块首次加载后会被缓存,重复 require 拿到的是同一实例
JS
// ------- math.js(导出) -------
// ✅ 正确:给 module.exports 赋值
module.exports = {
  add: (a, b) => a + b,
  PI: 3.14159,
};

// ❌ 常见错误:这样写 exports 与 module.exports 断连,外部拿到 {}
// exports.add = (a, b) => a + b;

// ------- app.js(导入) -------
const math = require('./math');          // 同目录文件必须写 ./
console.log(math.add(1, 2));             // 3
console.log(require('./math') === math); // true:模块缓存
本节要点CommonJS 三件套:require 导入、module.exports 导出、exports 改名要小心。