Node.js 模块化
1.前言
Node.js 的模块系统是基于 CommonJS 规范实现的。在使用模块化开发时,主要涉及两个操作:定义模块 和 引入模块
2.模块定义
- 在 Node.js 中,每个 JavaScript 文件就是一个独立的模块。默认情况下,模块导出的是一个空对象
//引入一个空白的js文件
const empty = require('./empty.js')
console.log(empty) //打印 {}
- 这个默认导出的空对象就是 exports 对象本身。因此,通过为 exports 添加属性,即可将数据暴露给其他模块
//person.js 使用exports添加2个属性
exports.name = 'zs'
exports.age = 23
//引入person.js
const person = require('./person.js')
console.log(person) //打印 {name:'zs',age:23}
- 如果模块需要导出的是一个函数、类或已有对象(而非逐步添加属性),应直接使用 module.exports 重新赋值。此时,对 exports 的任何修改将不再生效,因为 exports 只是 module.exports 的初始引用
function sayHello(){
console.log('hello')
}
//module.exports用法
module.exports = sayHello
3.模块的引入
模块通过 require() 方法引入。其参数可以是:
- 本地文件路径(如 './some.js'),
- Node.js 内置核心模块(如 'http'、'fs'、'path' 等),
- 第三方 npm 包名称(如 'express')
路径解析规则如下:
- 如果是相对/绝对路径
- Node.js 会直接加载指定路径的文件,且会自动补足扩展名 .js → .json → .node
- 若路径指向目录,则依次查找:index.js → index.node
- 如果不是路径(如 'vue'):
- 首先检查是否为 Node.js 核心模块,若是则直接加载
- 否则,视为 npm 安装的第三方模块,从 node_modules 中 package.json(main 字段) -> index.js → index.node
//引入内置模块 http模块
const http = require('http')
//引入npm包模块
const http = require('vue')
//引入本地自定义模块 根据路径读取
const http = require('./some.js')
- 注意:如果模块定义成一个对象,则可以使用ES6的解构赋值,筛选其中的某几个字段进行保存。但是要明白的是,在模块的过程中,实质是整体加载person.js模块,只是抽取了name,age进行缓存,这种加载称为“运行时加载”
const {name,age} = require('./person.js')
console.log(name,age) // zs 23
4.模块作用域中的“全局”变量
- 在运行某个js文件时,Node.js将js文件的代码放入某个自执行函数中(沙箱),这个自执行函数有一些参数,所以这些参数在js文件中是可以直接访问
- 查阅文档,这5个参数分别是:require/module/exports/当前js文件路径/当前目录路径
| 变量名称 | 说明 |
|---|---|
| require | 用来引入其他模块 |
| module | 用来暴漏当前模块 |
| exports | 用来暴漏当前模块 |
| __filename | 当前js文件路径 |
| __dirname | 当前目录路径 |
console.log('typeof require = ',typeof require)
console.log('typeof module = ',typeof module)
console.log('typeof exports = ',typeof exports)
//输出
typeof require = function
typeof module = object
typeof exports = object

浙公网安备 33010602011771号