在 Node.js 中运行 ECMAScript(ES)代码,通常有几种方式,取决于你用的是 Node 版本 和 ES 模块(ESM)还是 CommonJS。
// index.js
const msg = "Hello ECMAScript";
console.log(msg);
node index.js
✅ Node 本身支持 ECMAScript 语法(let / const / 箭头函数等)
.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
// index.js
const path = require('path');
console.log(path.resolve());
运行:
node index.js
Node 12+ 已原生支持:
const getData = async () => {
const res = await fetch('https://example.com');
console.log(res.status);
};
getData();
✅ Node 18+ 支持
fetch
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 版本,我可以给你更精确的方案。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。