What is parent-module?
The parent-module npm package allows you to find and require the parent module of a current module, which is useful in situations where you need to interact with or modify the behavior of the module that required your module. This can be particularly useful for plugins or modules that extend or modify the functionality of other modules.
What are parent-module's main functionalities?
Find and require the parent module
This feature allows you to find and require the parent module of the current module. The code sample demonstrates how to require the parent-module package and then use it to get the parent module. The 'parent' variable will contain the module object of the parent, and you can access properties such as 'filename' to get the file name of the parent module.
const parentModule = require('parent-module');
const parent = parentModule();
console.log(parent.filename);
Other packages similar to parent-module
caller
The caller package allows you to get the file path of the caller function. It is similar to parent-module in that it helps you identify the calling module, but it focuses on the function call stack rather than the module hierarchy.
caller-path
The caller-path package is similar to caller, providing the path of the caller function. It is a more focused tool compared to parent-module, which provides the entire parent module object.
require-main-filename
This package is used to always get the main entry point file path of a module, regardless of the environment (e.g., when using a module bundler). It differs from parent-module by focusing on the entry point file rather than the immediate parent module.
parent-module
Get the path of the parent module
Node.js exposes module.parent
, but it only gives you the first cached parent, which is not necessarily the actual parent.
Install
npm install parent-module
Usage
import parentModule from 'parent-module';
export default function bar() {
console.log(parentModule());
};
import bar from './bar.js';
bar();
API
parentModule(filePath?)
By default, it will return the path of the immediate parent.
filePath
Type: string
Default: __filename
The file path of the module of which to get the parent path.
Useful if you want it to work multiple module levels down.
Tip
Combine it with read-pkg-up
to read the package.json of the parent module.
import path from 'node:path';
import {readPackageUpSync} from 'read-pkg-up';
import parentModule from 'parent-module';
console.log(readPackageUpSync({cwd: path.dirname(parentModule())}).pkg);