Node.js 环境中如何正确使用 ES6(ES2015+)的语法和特性,这是一个非常基础且重要的问题,因为 Node.js 对 ES6 特性的支持是分阶段的,且不同版本的支持程度不同。
一、Node.js 对 ES6 的原生支持
首先要明确,现代版本的 Node.js(v14+)已经原生支持绝大多数 ES6 特性,无需额外配置就能直接使用大部分核心语法:
- 箭头函数
() => {} - let/const 声明
- 解构赋值
- 模板字符串
- 类(Class)
- Promise
- 展开 / 剩余运算符
- Map/Set 等
1. 直接运行(支持大部分语法)
创建 test.js 文件:
// ES6 示例代码
const greeting = 'Hello';
const name = 'Node.js';
const sayHi = () => `${greeting}, ${name}!`;
class User {
constructor(name) {
this.name = name;
}
greet() {
return `Hi, I'm ${this.name}`;
}
}
const user = new User('ES6');
console.log(sayHi()); // 输出: Hello, Node.js!
console.log(user.greet()); // 输出: Hi, I'm ES6
直接运行:
node test.js
二、使用 ES6 模块(import/export)
Node.js 默认使用 CommonJS 模块(require/module.exports),要使用 ES6 的 import/export 模块系统,需要额外配置:
方法 1:修改文件扩展名
将 .js 文件改为 .mjs,Node.js 会自动将其识别为 ES6 模块:
- 创建
module.mjs:// 导出模块 export const PI = 3.14159; export function calculateArea(r) { return PI * r * r; } - 创建
main.mjs:// 导入模块 import { PI, calculateArea } from './module.mjs'; console.log(PI); // 输出: 3.14159 console.log(calculateArea(2)); // 输出: 12.56636 - 运行:
node main.mjs
方法 2:通过 package.json 配置(推荐)
在项目根目录创建 package.json,添加 "type": "module",这样所有 .js 文件都会被识别为 ES6 模块:
- 初始化 package.json(若没有):
npm init -y
- 修改 package.json:
{ "name": "es6-demo", "version": "1.0.0", "type": "module", // 关键配置 "main": "index.js" } - 创建
index.js:import { PI, calculateArea } from './module.js'; console.log(calculateArea(3)); // 输出: 28.27431 - 运行:
node index.js
三、兼容低版本 Node.js(可选)
如果需要在低版本 Node.js(v12 及以下)中使用完整的 ES6 特性,可以借助 babel 转译:
- 安装依赖:
npm install @babel/core @babel/cli @babel/preset-env --save-dev
- 创建
.babelrc配置文件:{ "presets": ["@babel/preset-env"] } - 转译并运行:
- 转译代码:
npx babel src --out-dir dist - 运行转译后的代码:
node dist/index.js
- 转译代码:
总结
- 现代 Node.js(v14+)原生支持大部分 ES6 语法(箭头函数、类、解构等),可直接运行。
- 使用 ES6 模块(
import/export)需通过.mjs扩展名或package.json中配置"type": "module"。 - 低版本 Node.js 可通过 Babel 转译实现 ES6 特性的兼容。
注意事项
- 配置
"type": "module"后,不能再混用require/module.exports,需统一使用import/export。 - 导入本地文件时必须写完整扩展名(如
./module.js,不能省略.js)。 - Node.js 版本越高,对 ES6 特性的支持越完善,建议使用 LTS 版本(如 v18、v20)。