DEP0144: module.parent


类型: 仅文档(支持 --pending-deprecation

CommonJS 模块可以使用 module.parent 访问第一个需要它的模块。 此特性已被弃用,因为它在存在 ECMAScript 模块的情况下无法始终如一地工作,并且因为它给出了 CommonJS 模块图的不准确表示。

一些模块用它来检查它们是否是当前进程的入口点。 而是,建议比较 require.mainmodule

if (require.main === module) {
  // 仅当当前文件是入口点时才会运行的代码部分。
}

当查找需要当前的 CommonJS 模块时,可以使用 require.cachemodule.children

const moduleParents = Object.values(require.cache)
  .filter((m) => m.children.includes(module));

Type: Documentation-only (supports --pending-deprecation)

A CommonJS module can access the first module that required it using module.parent. This feature is deprecated because it does not work consistently in the presence of ECMAScript modules and because it gives an inaccurate representation of the CommonJS module graph.

Some modules use it to check if they are the entry point of the current process. Instead, it is recommended to compare require.main and module:

if (require.main === module) {
  // Code section that will run only if current file is the entry point.
}

When looking for the CommonJS modules that have required the current one, require.cache and module.children can be used:

const moduleParents = Object.values(require.cache)
  .filter((m) => m.children.includes(module));