Node.js 12+ 有新的命令行选项 --input-type 来在 Bash Heredoc 中运行脚本。但是,似乎无法找到./node_modules中安装的Node.js模块
这是我安装模块的方法:
cd test
npm i moment
并使用heredoc中的脚本运行Node.js:
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 错误。有什么解决办法吗?
最佳答案
正如这个答案中提到的:https://stackoverflow.com/a/55568877/5581893
目前无法在 Node.js REPL 中加载模块(使用 Bash heredoc 运行“node”),除了那些内置模块,例如:fs、http 等。
所以现在唯一的解决方法就是这样,例如“moment”模块:
#bash script
echo '//begin
import moment from "moment";
...
//end' >test.mjs
node --experimental-modules test.mjs
关于node.js - 使用 --input-type 时无法加载本地目录 Node.js 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56270188/