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