在 Node 中使用 CommonJS 模块时,您可以使用 require.main === module
检测脚本是否正在从命令行运行。
在 Node 中使用 ES 模块(使用 --experimental-modules
标志)时,检测脚本是否正在从命令行运行的等效方法是什么?
最佳答案
使用
if (import.meta.url === `file://${process.argv[1]}`) {
// module was not imported but called directly
}
参见 MDN docs on import.meta
了解详情。
2021 年 9 月 27 日更新
也许更健壮,但涉及一个 extra import (通过 Rich Harris )
import {pathToFileURL} from 'url'
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
// module was not imported but called directly
}
关于javascript - 检测 ES 模块是否从 Node 中的命令行运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57838022/