CommonJS 是一种模块化规范,最初是为了在服务器端(例如 Node.js)实现模块化而设计的,它使用 require() 函数来引入模块,使用 module.exports 对象来导出模块。以下是关于 CommonJS 模块化的一些重要内容:
1. 导出模块:
- 使用
module.exports对象来导出模块,可以将任何 JavaScript 对象赋值给module.exports。
2. 引入模块:
- 使用
require()函数来引入模块,该函数接受模块的路径作为参数,并返回导出的模块对象。
3. 模块缓存:
- Node.js 会将已经加载的模块缓存起来,以便在下次引入时直接从缓存中获取,提高性能。
示例:
假设有两个文件,分别为 module1.js 和 main.js。
module1.js:
// 导出模块
const name = "John";
function greet() {
console.log(`Hello, ${name}!`);
}
module.exports = {
name: name,
greet: greet
};
main.js:
// 引入模块
const module1 = require('./module1.js');
// 使用模块中的内容
console.log(module1.name); // 输出: John
module1.greet(); // 输出: Hello, John!