是否有方法获取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重新打包每个组件?