Node.js 模块系统
1. import.meta.url 是什么
import.meta.url 是 ES 模块的语法,表示当前文件的 URL 路径。
javascript
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url); // 把 import.meta.url(文件 URL)转换成文件路径
__filename 在 CommonJS 中是全局存在的,但在 ES 模块中需要通过 import.meta.url 转换得到。
2. Node.js 默认模块规范
Node.js 默认使用 CommonJS 规范 (require() / module.exports)。
ES 模块(import / export 语法)需要显式声明才能使用。
如何启用 ES 模块
有三种方式:
package.json声明"type": "module"--- 所有.js文件被视为 ES 模块- 文件使用
.mjs扩展名 --- 强制作为 ES 模块 - 文件使用
.cjs扩展名 --- 强制作为 CommonJS 模块
示例
json
// package.json
{
"name": "my-project",
"type": "module"
}
未声明时,Node.js 会把 .js 文件当作 CommonJS,产生警告:
[MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file://... is not specified
3. CommonJS vs ES 模块
| 特性 | CommonJS | ES 模块 |
|---|---|---|
| 语法 | require() / module.exports |
import / export |
| 加载 | 同步 | 异步 |
| 运行时 | 项目初始化时 | 静态解析(编译时) |
| 默认 | 是 | 否(需声明) |