如何使__dirname指向调用该模块的文件所在目录?
问题:如何让__dirname模块返回调用文件的目录?
目录结构
utils __dirname.js app.js
当前代码
utils/__dirname.js
import { dirname } from 'path'; import { fileURLToPath } from 'url'; export const __dirname = dirname(fileURLToPath(import.meta.url));
app.js
import { __dirname } from './utils/__dirname.js'; console.log(__dirname);
当前输出
src/utils
解决方案
当前的__dirname常量是固定基于自身文件的import.meta.url计算的,所以不管哪个文件导入,都只会指向utils目录。要让它返回调用文件的目录,核心是让调用者传入自己的模块URL,具体改法如下:
1. 修改utils/__dirname.js
把导出的常量改成一个接收参数的函数:
import { dirname } from 'path'; import { fileURLToPath } from 'url'; export const getDirname = (moduleUrl) => dirname(fileURLToPath(moduleUrl));
2. 在调用文件中使用
导入函数后,传入当前文件的import.meta.url:
import { getDirname } from './utils/__dirname.js'; const __dirname = getDirname(import.meta.url); console.log(__dirname);
这样运行app.js时,输出就会变成app.js所在的目录(比如src),其他文件导入这个函数时,只要传入自身的import.meta.url,就能获取到自己所在的目录。
内容的提问来源于stack exchange,提问作者Taste of Leaving
相关产品推荐
相关产品推荐

