使用 --input-type 时无法加载本地目录 Node.js 模块

Can not load local dir Node.js modules when using --input-type

Node.js 12+ 有新的命令行选项 --input-type to 运行 script inside Bash heredoc。但是,它似乎无法找到安装在 ./node_modules

中的 Node.js 模块

以下是我安装模块的方法:

cd test
npm i moment

和 运行 Node.js 以及 heredoc 中的脚本:

cd test

#this works
node --experimental-modules --input-type module <<<"import fs from 'fs'"

#this doesn't
node --experimental-modules --input-type module <<<"import moment from 'moment'"

即使使用 全局选项 -g 安装 moment,它仍然会产生 ERR_MODULE_NOT_FOUND 错误。有什么解决办法吗?

如本回答所述:

目前无法在 Node.js REPL(运行 'node' 和 Bash heredoc)中加载模块,除了那些 built-in 模块,例如:fs , http 等

所以现在唯一的work-around是这样的,例如'moment'模块:

#bash script
echo '//begin
import moment from "moment";
...
//end' >test.mjs

node --experimental-modules test.mjs