如何从 shell 脚本评估 ecmascript 模块?

问题描述 投票:0回答:1

我正在将 .js 文件转换为 .mjs 文件,但遇到了问题。

我使用 shell 脚本中的 JS 函数,如下所示:

$ node --eval "require(\"./foo.js\").bar($a, $b)"

变成

foo.mjs
后,运行:

$ node --experimental-modules --eval "import foo from \"./foo.mjs\"; foo.bar($a, $b)"

产量

[eval]:1
import foo from "./foo.mjs"; foo.bar(, )
^^^^^^

SyntaxError: Cannot use import statement outside a module
$ node --experimental-modules foo.mjs
如果我添加

console.log

,则
不执行任何操作或打印“Hello World”。我需要使用参数运行其
bar()
函数,但不想为此添加中间脚本。

node.js ecmascript-6
1个回答
0
投票

您可以使用选项指定输入类型

--input-type
:

这将 Node.js 配置为将

--eval
STDIN
输入解释为 CommonJS 或 ES 模块。有效值为
commonjs
module
。默认为
commonjs
,除非使用
--experimental-default-type=module

所以这样做:

node --input-type=module --eval "import foo from \"./foo.mjs\"; foo.bar($a, $b)"
© www.soinside.com 2019 - 2024. All rights reserved.