nodejs(模块化CommonJS)

31 阅读1分钟

认识模块化系统: CommonJS

CommonJS 是一种 模块规范(module specification) ,最早用于 Node.js
它的目标是让 JavaScript 能像其他语言(如 Java、Python)那样使用模块化编程。

在 CommonJS 中:

  • 每个文件就是一个独立的 模块
  • 模块之间通过 require() 导入。
  • 模块通过 module.exportsexports 导出。

1. Node.js默认支持CommonJS

// math.js
const add = (a, b) => a + b
const sub = (a, b) => a - b

// 导出模块(方式一)
module.exports = {
  add,
  sub
}

// 或者(方式二)
exports.add = add
exports.sub = sub

2. 导入模块

// main.js
const math = require('./math')  // 相对路径导入

console.log(math.add(3, 4)) // 7
console.log(math.sub(9, 5)) // 4