温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

ecmascript如何在node运行

发布时间:2026-08-31 20:49:49 来源:亿速云 阅读:93 作者:小樊 栏目:编程语言

在 Node.js 中运行 ECMAScript(ES)代码,通常有几种方式,取决于你用的是 Node 版本 和 ES 模块(ESM)还是 CommonJS。


一、直接用 Node 运行 JavaScript(ECMAScript)

1️⃣ 创建文件

// index.js
const msg = "Hello ECMAScript";
console.log(msg);

2️⃣ 运行

node index.js

✅ Node 本身支持 ECMAScript 语法(let / const / 箭头函数等)


二、使用 ES Module(import / export)

方式一:.mjs 文件(推荐)

// index.mjs
import os from 'os';

console.log(os.platform());

运行:

node index.mjs

方式二:在 package.json 中启用 ESM

{
  "type": "module"
}

然后:

// index.js
import fs from 'fs';
console.log(fs.readdirSync('.'));

运行:

node index.js

三、CommonJS(Node 默认)

// index.js
const path = require('path');
console.log(path.resolve());

运行:

node index.js

四、使用现代 ES 特性(async / await / 可选链)

Node 12+ 已原生支持:

const getData = async () => {
  const res = await fetch('https://example.com');
  console.log(res.status);
};

getData();

✅ Node 18+ 支持 fetch


五、使用 Babel(兼容老 Node)

npm install @babel/core @babel/node @babel/preset-env

.babelrc

{
  "presets": ["@babel/preset-env"]
}

运行:

npx babel-node index.js

六、常见错误

❌ Cannot use import statement outside a module ✅ 使用 .mjs 或 package.json 加 "type": "module"


总结

方式 适合
node xxx.js CommonJS
node xxx.mjs ES Module
"type":"module" 项目级 ESM
Babel 老环境

如果你有 具体代码或 Node 版本,我可以给你更精确的方案。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手