Node.js 模块系统概述
模块系统让代码可复用、易维护,是 Node.js 架构的基础。
什么是模块
模块是一个独立的代码单元,封装特定功能,通过导出和引入与其他模块交互。
JavaScript
// 每个文件就是一个模块
// utils.js
const helper = () => console.log('helper');
module.exports = { helper };
// app.js
const utils = require('./utils');
utils.helper();
模块类型
| 类型 | 说明 | 引入方式 |
|---|---|---|
| 核心模块 | Node.js 内置 | require('fs') |
| 文件模块 | 用户自定义 | require('./utils') |
| 第三方模块 | npm 安装 | require('express') |
模块作用域
每个模块都有独立作用域,变量不会污染全局:
JavaScript
// a.js
var x = 1;
console.log(global.x); // undefined(x 是模块局部)
// b.js
var x = 2; // 与 a.js 的 x 完全独立
模块包装
Node.js 自动将模块代码包装:
JavaScript
// 原代码
const name = 'module';
module.exports = name;
// 包装后执行
(function(exports, require, module, __filename, __dirname) {
const name = 'module';
module.exports = name;
});
每个模块可用的变量:
| 变量 | 说明 |
|---|---|
| exports | 导出对象引用 |
| require | 加载模块函数 |
| module | 当前模块对象 |
| __filename | 当前文件绝对路径 |
| __dirname | 当前文件所在目录 |
导入导出方式
CommonJS
JavaScript
// 导出
module.exports = { name: 'test' };
exports.func = () => {};
// 导入
const mod = require('./mod');
ES Modules
JavaScript
// 导出
export const name = 'test';
export default { name: 'test' };
// 导入
import { name } from './mod.mjs';
import mod from './mod.mjs';
模块化优势
代码复用
JavaScript
// 将通用功能封装为模块
// helpers.js
module.exports = {
formatDate: (date) => date.toISOString(),
parseJSON: (str) => JSON.parse(str)
};
// 多个项目复用
const helpers = require('./helpers');
命名空间隔离
JavaScript
// 不同模块同名变量不会冲突
// config.js
const name = 'config';
// user.js
const name = 'user'; // 完全独立
依赖管理
JavaScript
// 明确的依赖声明
const fs = require('fs');
const path = require('path');
const config = require('./config');
易于测试
JavaScript
// 单个模块可独立测试
const math = require('./math');
assert.equal(math.add(1, 2), 3);
模块组织建议
JavaScript
// 项目结构示例
project/
├── src/
│ ├── modules/
│ │ ├── user/
│ │ │ ├── index.js
│ │ │ ├── model.js
│ │ │ └── service.js
│ │ └── product/
│ │ └── index.js
│ ├── utils/
│ │ └── index.js
│ ├── config/
│ │ └── index.js
│ └── app.js
├── package.json
要点总结
- 模块是代码单元,有独立作用域
- 核心模块、文件模块、第三方模块三种类型
- CommonJS 使用 require/module.exports
- ES Modules 使用 import/export
- 模块化实现代码复用、隔离命名空间、管理依赖
📝 发现内容有误?点击此处直接编辑