是否有方法获取Node.js中加载模块的文件路径?

是否有方法获取Node.js中加载模块的文件路径?,node.js,Node.js,给定已加载的模块,是否可以获取其文件路径 const MyModule = require('./MyModule'); const MyOtherModule = require('../otherfolder/MyOtherModule'); function print(){ console.log(thisIsThePathTo(MyModule)); <--- Should print the absolute path of the loaded module

给定已加载的模块,是否可以获取其文件路径

const MyModule = require('./MyModule');
const MyOtherModule = require('../otherfolder/MyOtherModule');

function print(){
   console.log(thisIsThePathTo(MyModule));  <--- Should print the absolute path of the loaded module
   console.log(thisIsThePathTo(MyOtherModule));  <--- Should print the absolute path of the loaded module
}
const MyModule=require('./MyModule');
const MyOtherModule=require('../otherfolder/MyOtherModule');
函数打印(){
log(thisIsThePathTo(MyModule));的文档描述了
模块
对象

模块有一个
id
和一个
路径
,但是它们没有导出。您可以将这些属性添加到
模块。导出
对象以导出它们。然后,在单独的模块中,您可以通过
MyOtherModule.id
MyOtherModule.path

比如说,

MyOtherModule/index.js
中:

myOtherModuleFunction=function(){
console.log('这是模块2')
}
module.exports={
//展开module.exports中的所有属性
…模块,
//然后添加导出
导出:myOtherModuleFunction
}
MyModule/MyModule.js

module.exports={
…模块,
导出:{someFunction:()=>console.log('MyModule')}
}
MyModule/index.js
中:

const MyModule=require('./MyModule');
常量MyOtherModule=require('../../MyOtherModule/');
函数thisIsThePathTo(模块){
返回模块路径
}
函数打印(){
日志(thisIsThePathTo(MyModule))
console.log(thisIsThePathTo(MyOtherModule))
}
打印()
运行
节点src/MyModule/index.js
输出:

/.../stackoverflow/62043302/src/MyModule/
/.../stackoverflow/62043302/src/MyOtherModule
如果您打印的是
module.id
,而不是
module.path
,您将得到:

/.../stackoverflow/62043302/src/MyModule/index.js
/.../stackoverflow/62043302/src/MyOtherModule/index.js
但是,扩展所有属性包括
module.children
module.parent
,并且您在访问时还必须使用
module.exports
,因此您可能只希望包括
id
path
,如下所示:

myOtherModuleFunction=function(){
console.log('这是模块2')
}
常量{id,path}=模块
module.exports={
身份证件
路径
肌热调节功能,
}```
并要求:
```js
const{id:otherModuleId,myOtherModuleFunction}=require('MyOtherModule')

这可能会变得混乱。如果您正在导入未编写的模块,您将无法选择查找
id
路径
(除非作者将其添加到
模块.exports
)(

Nice:)虽然我希望得到一些不需要改变原版的东西component@Udi是的,不幸的是,我不确定这是怎么可能的。也许有一种方法可以用webpack重新打包每个组件?