【问题标题】:How do I detect if an ES Module is the main module?如何检测 ES Module 是否是主模块?
【发布时间】:2021-01-18 15:47:36
【问题描述】:

如何检测 ECMAScript 模块是否是主模块?这对于 CommonJS 模块来说很容易(参见 Detect if called through require or directly by command line)。

  • 没有requirerequire.main

  • 没有process.mainModule

  • import.meta没有线索,只有url

【问题讨论】:

标签: javascript node.js es6-modules


【解决方案1】:

你可以使用es-main

来自包自述文件:

import esMain from 'es-main';
 
if (esMain(import.meta)) {
  // Module run directly.
}

注意:该模块只能在 Node.JS 环境中工作,因为模块代码使用的是原生 Node.JS 模块。

【讨论】:

  • es-main does fileURLToPath(import.meta.url) === process.argv[1],如果脚本名称中缺少扩展名,则可能会从模块路径中删除扩展名。
猜你喜欢
  • 2020-01-10
  • 1970-01-01
  • 2019-03-21
  • 2017-09-07
  • 2017-12-01
  • 2016-10-10
  • 2015-11-12
  • 2020-04-03
  • 2015-08-09
相关资源
最近更新 更多