在 Node 中使用 CommonJS 模块时,您可以使用以下命令检测脚本是否正在从命令行运行require.main === module
.
在 Node 中使用 ES 模块时,检测脚本是否正在从命令行运行的等效方法是什么(使用--experimental-modules
flag)?
Use
if (import.meta.url === `file://${process.argv[1]}`) {
// module was not imported but called directly
}
See the MDN 文档上import.meta https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import.meta#using_import.meta了解详情。
2021 年 9 月 27 日更新
也许更强大,但涉及额外进口 https://nodejs.org/api/url.html#url_url_pathtofileurl_path (via 里奇·哈里斯 https://twitter.com/Rich_Harris/status/1355289863130673153)
import { pathToFileURL } from 'url'
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
// module was not imported but called directly
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)