5A景区网站建设

JavaScript CommonJS 模块化学习

CommonJS 是一种模块化规范,最初是为了在服务器端(例如 Node.js)实现模块化而设计的,它使用 require() 函数来引入模块,使用 module.exports 对象来导出模块。以下是关于 CommonJS 模块化的一些重要内容:

1. 导出模块:

2. 引入模块:

3. 模块缓存:

示例:

假设有两个文件,分别为 module1.jsmain.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!

 在这个示例中,module1.js 导出了一个包含 name 属性和 greet() 方法的对象,然后在 main.js 中使用 require() 函数引入了 module1.js 模块,并使用导出的属性和方法。CommonJS 模块化规范在 Node.js 中得到了广泛应用,也为 JavaScript 在服务器端的发展提供了基础。

退出移动版