深入浅出 Node.js 总结 —— 模块机制(1)
2023-10-27 15:04:44
Node.js 模块机制概述
Node.js 的模块机制由 Node.js 自行定义并实现,在 CommonJS 规范的基础上进行了取舍和扩展。它为 JavaScript 引入了模块的概念,方便了代码的复用和组织。
Node.js 模块是独立的 JavaScript 文件,每个模块都有自己的作用域。模块可以通过 require() 方法或 import 语句进行加载,然后就可以使用模块中的变量、函数和类。
Node.js 模块机制的主要优点包括:
- 模块化开发:可以将代码分解成更小的模块,便于维护和复用。
- 代码隔离:每个模块都有自己的作用域,可以防止变量和函数命名冲突。
- 提高性能:Node.js 会对引入过的模块进行缓存,以减少二次引入时的开销。
Node.js 模块的定义
Node.js 模块是一个独立的 JavaScript 文件,可以包含变量、函数和类。模块的文件名通常以 .js 为后缀,例如:
my-module.js
模块的内容可以是任何合法的 JavaScript 代码,例如:
// my-module.js
const PI = 3.14;
function sum(a, b) {
return a + b;
}
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// 将模块导出
module.exports = {
PI,
sum,
Person
};
在上面的示例中,my-module.js 模块导出了三个值:PI、sum 和 Person 类。这些值可以在其他模块中使用,例如:
// other-module.js
const { PI, sum, Person } = require('./my-module');
console.log(PI); // 3.14
console.log(sum(1, 2)); // 3
const person = new Person('John', 30);
person.greet(); // Hello, my name is John and I am 30 years old.
Node.js 模块的加载
Node.js 模块可以通过 require() 方法或 import 语句进行加载。
require() 方法是 Node.js 加载模块的传统方式,语法如下:
const module = require('module-name');
module-name 可以是模块的文件名(相对于当前模块的位置)或内置模块的名称。例如,要加载 my-module.js 模块,可以这样写:
const myModule = require('./my-module');
import 语句是 ES6 引入的模块加载方式,语法如下:
import { member1, member2, ... } from 'module-name';
member1、member2 等是模块中要导入的变量、函数或类。例如,要从 my-module.js 模块中导入 PI、sum 和 Person 类,可以这样写:
import { PI, sum, Person } from './my-module';
Node.js 模块的缓存机制
Node.js 对引入过的模块都会进行缓存,以减少二次引入时的开销。==Node缓存的是编译和执行之后的对象== require()方法/import语句对于相同模块的二次加载都一律采用缓存优先的方式,…