如何检测 ES 模块是否是主模块?

How do I detect if an ES Module is the main module?

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

你可以使用 es-main.

来自包自述文件:

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

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

我不知道在浏览器中,但在带有 .mjs 模块的节点中,以下似乎有效:

const isMainModule = import.meta.url.endsWith(process.argv[1])

解释:

import.meta.url 以协议 file:// 开头,例如:

file:///path/to/my/module.mjs

但在节点中,process.argv[1]更短,例如:

/path/to/my/module.mjs

所以 endsWith 在这里很有用。