解決vite.config.js無法使用__dirname的問題
vite.config.js無法使用__dirname
__dirname 是 commonjs 規(guī)范的內(nèi)置變量。
如果使用了 esm 是不會自動注入這個變量的。
在 commonjs 中,注入了 __dirname , __filename , module , exports , require 五個內(nèi)置變量用于實現(xiàn)導(dǎo)入導(dǎo)出的能力。而在 esm 中實現(xiàn)方式是不一樣的。
在 esm 中,顯然模塊的導(dǎo)入導(dǎo)出使用 export/import ,自然不會再用 exports/require ,同理 __dirname , __filename 也有對應(yīng)的寫法。
方法一
首先,使用 node:url 模塊中的URL和 fileURLToPath 函數(shù)對URL進(jìn)行解析和轉(zhuǎn)換。
然后,使用URL構(gòu)造函數(shù)的第一個參數(shù)傳入".",即當(dāng)前目錄的相對路徑,再結(jié)合 import.meta.url 來獲取當(dāng)前目錄的URL。
最后,使用 fileURLToPath 函數(shù)將URL轉(zhuǎn)換為文件路徑,從而獲取所需的 __dirname
// 方法一
import { URL, fileURLToPath } from "node:url";
// 獲取__filename
function getCurrnetFile () {
return fileURLToPath(import.meta.url);
}
// 獲取__dirname
function getCurrnetDir () {
const url = new URL(".", import.meta.url);
return fileURLToPath(url);
}方法二
這種方法使用了 node:path 模塊中的 dirname 函數(shù)和 node:url 模塊中的 fileURLToPath 函數(shù)。
首先,使用 fileURLToPath 函數(shù)將 import.meta.url 轉(zhuǎn)換為文件路徑,獲取當(dāng)前文件的路徑 __filename 。
然后,使用 dirname 函數(shù)將文件路徑轉(zhuǎn)換為所在目錄的路徑 __dirname ,從而得到了 __dirname 。
// 方法二
import { dirname } from "node:path";
import { fileURLToPath } from "node:url";
// 獲取__filename
function getCurrnetFile () {
return fileURLToPath(import.meta.url);
}
// 獲取__dirname
function getCurrnetDir () {
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
return __dirname;
}可以看到使用了一個關(guān)鍵API import.meta.url ,其實 import.meta 是 ECMA 規(guī)范的一部分:
The import.meta object exposes context-specific metadata to a JavaScript module.
It contains information about the module, like the module’s URL.
言下之意, import.meta 提供了一個模塊的上下文信息。
總之,以上兩種方法都是在ESM中模擬獲取 __dirname 的功能。
它們利用 import.meta.url 獲取模塊的URL,然后使用相關(guān)的Node.js內(nèi)置模塊對URL或文件路徑進(jìn)行解析,從而得到當(dāng)前模塊所在的目錄路徑
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue3中g(shù)etCurrentInstance獲取組件踩坑及解決
這篇文章主要介紹了vue3中g(shù)etCurrentInstance獲取組件踩坑及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-06-06
maptalks+three.js+vue webpack實現(xiàn)二維地圖上貼三維模型操作
這篇文章主要介紹了maptalks+three.js+vue webpack實現(xiàn)二維地圖上貼三維模型操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
electron踩坑之remote of undefined的解決
這篇文章主要介紹了electron踩坑之remote of undefined的解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
vue項目上線路徑跳轉(zhuǎn)無效(404問題)的解決
文章主要介紹了兩種解決Vue?Router在Nginx部署后路由無法跳轉(zhuǎn)問題的方法:法一是在Vue?Router中將路由模式改為hash模式,利用URL的hash部分來模擬完整URL,這樣不會向后端發(fā)送請求;法二是在Nginx中配置路由,將所有請求重定向到index.html,以支持history模式的Vue?Router2025-10-10

