javascript - 使用 Bash heredoc 在 Bash 终端中运行 ES6 代码

标签 javascript node.js bash ecmascript-6 heredoc

ES5 代码可以在终端中使用 Bash heredoc 轻松运行:

node <<HEREDOC
  var fs = require("fs");
  ...
HEREDOC

但 ES6 代码无法运行,即使使用正确的 --experimental-modules 标志也是如此:

node --experimental-modules <<HEREDOC
  import fs from "fs";
  ...
HEREDOC

显示的错误是:

(node:4130) ExperimentalWarning: The ESM module loader is experimental.
[stdin]:1
import fs from "fs";
       ^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:83:7)
    at createScript (vm.js:267:10)
    at Proxy.runInThisContext (vm.js:319:10)
    at Object.<anonymous> ([stdin]-wrapper:6:22)
    at Module._compile (internal/modules/cjs/loader.js:722:30)
    at evalScript (internal/bootstrap/node.js:670:27)
    at ReadStream.<anonymous> (internal/bootstrap/node.js:340:15)
    at ReadStream.emit (events.js:187:15)
    at endReadableNT (_stream_readable.js:1098:12)
    at process.internalTickCallback (internal/process/next_tick.js:72:19)

它确实显示此信息“ExperimentalWarning:ESM 模块加载器是实验性的。”这意味着 Node.js 使用 ES6 模块功能正确运行,但是,import 关键字不起作用

如何使用 Bash heredoc 在终端中内联运行 ES6 代码?我知道我可以将代码写入文件以正常加载为 ES6 模块,但它是一个简短的临时代码,应该在 heredoc 中更好。

最佳答案

更新:
从 Node.js 14 开始,标志 --experimental-modules 不再需要,它已经在 Node.js 中默认用于 .mjs 文件,也用于 heredoc,但是 CLI 上仍然需要 --input-type 因为 ES5 或 ES6 仍然应该为 heredoc 指定:

node --input-type module <<HEREDOC
  //example:
  import fs from "fs";
HEREDOC

较早的指南:
经过调查,Node 11 根本不支持来自标准输入的 ES 模块,如果你想在 Node 11 中使用模块,你需要将它们放在一个文件中。

对于 Node 12(当前未发布,但您可以使用 npm i -g node-nightly 进行尝试),您可以使用标志 --entry-type=module将标准输入用作模块。

node-nightly 中,以下工作正常:

node-nightly --experimental-modules --entry-type=module <<HEREDOC
  import fs from 'fs'
  console.log(fs);
HEREDOC

编辑:

正如@Jamesernator 在评论中指出的那样,对于 v13 中的每晚 Node ,请使用“--input-type”而不是“--entry-type”。

并且只支持内置模块,即。 'import' 将无法在本地目录中找到模块,也无法找到使用 '-g' 标志安装的全局模块。相关问题:https://github.com/nodejs/node/issues/19570

关于javascript - 使用 Bash heredoc 在 Bash 终端中运行 ES6 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55568214/

相关文章:

javascript - Mongoose 中的保存方法失败

node.js - 通过express js 和 bodyParser 实现安全文件上传

BASH:根据公共(public)字段名称加入 2 个 CSV 文件

javascript - 我的 javascript 函数逻辑有什么问题?

JavaScript 正则表达式 dotall 和 global 标志

node.js - socket.io无法连接react-native和nodejs

macos - gfortran : fatal error: no input files compilation terminated

linux - 使用 UNIX BASH 将文件复制到其他虚拟机

javascript - 如何在jquery中操作具有所有条件的复选框

javascript - Node : Have a setInterval loop only while another variable is true