Node.js 内置模块导入:node: 前缀的作用
在导入 Node.js 内置模块时添加 node: 前缀有以下作用:
1. 明确标识内置模块
node:fs 明确表示这是 Node.js 的内置模块,而不是第三方 npm 包或本地文件。
2. 避免命名冲突
如果有第三方包也叫 fs,使用 node:fs 可以确保导入的是 Node.js 内置的 fs 模块。
3. 提高代码可读性
一眼就能识别哪些是 Node.js 内置模块,哪些是第三方依赖:
import fs from 'node:fs' // Node.js 内置模块
import express from 'express' // npm 包
import { helper } from './utils' // 本地文件
4. 打包工具优化
现代打包工具(如 webpack、esbuild、Rollup)能更好地识别和处理内置模块,避免将其打包进 bundle。
版本支持
这是 Node.js v12+ 引入的特性,现在已成为推荐的最佳实践。
常见内置模块示例
import fs from 'node:fs'
import path from 'node:path'
import http from 'node:http'
import crypto from 'node:crypto'
import { fileURLToPath } from 'node:url'