我正在将 .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()
函数,但不想为此添加中间脚本。
--input-type
:
这将 Node.js 配置为将
或--eval
输入解释为 CommonJS 或 ES 模块。有效值为STDIN
或commonjs
。默认为module
,除非使用commonjs
。--experimental-default-type=module
所以这样做:
node --input-type=module --eval "import foo from \"./foo.mjs\"; foo.bar($a, $b)"