What is which-module?
The which-module npm package is designed to help developers identify the module object for a given request. This is particularly useful in scenarios where you need to know which module is calling a function or when debugging to understand the module dependency tree. It provides a straightforward API to get the module based on a reference to it.
What are which-module's main functionalities?
Identifying the module for a given reference
This feature allows developers to find out the module object for a specific reference. In the code sample, `which-module` is used to identify the module object for 'some-module' by accessing it through `require.cache` and `require.resolve`. This can be particularly useful for debugging purposes or when implementing custom module loaders or handlers.
const whichModule = require('which-module');
const moduleInfo = whichModule(require.cache[require.resolve('some-module')]);
console.log(moduleInfo);
Other packages similar to which-module
resolve
The 'resolve' package is similar to 'which-module' in that it helps with module resolution. However, 'resolve' focuses more on asynchronously resolving the path of a module according to the Node.js `require.resolve` algorithm, rather than identifying the module object itself. It's more about finding where a module is located rather than identifying the module's object.
caller
The 'caller' package provides functionality to identify the caller of a function, which can indirectly help in understanding module interactions. While 'which-module' directly identifies the module object for a given reference, 'caller' helps in tracing back the call stack to see which module or function made the current call. This can be useful for debugging or tracking function calls across modules.
which-module
Find the module object for something that was require()d
Find the module
object in require.cache
for something that was require()
d
or import
ed - essentially a reverse require()
lookup.
Useful for libs that want to e.g. lookup a filename for a module or submodule
that it did not require()
itself.
Install and Usage
npm install --save which-module
const whichModule = require('which-module')
console.log(whichModule(require('something')))
API
whichModule(exported)
Return the module
object,
if any, that represents the given argument in the require.cache
.
exported
can be anything that was previously require()
d or import
ed as a
module, submodule, or dependency - which means exported
is identical to the
module.exports
returned by this method.
If exported
did not come from the exports
of a module
in require.cache
,
then this method returns null
.
License
ISC © Contributors