DEP0144:module.parent


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

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

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

¥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.

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

¥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.
} 

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

¥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));