There's a chicken-egg problem here: Vite expects to resolve .env files from project root, but project root can be made different by the config file.
So if we resolve .env before resolving the config file, we can only resolve it from CWD, which would then break the case where the user puts .env files in a nested root specified via config.
摘自Evan You的回復(fù)
今天在配置vite.config的時(shí)候使用到import.meta.env來(lái)設(shè)置項(xiàng)目路徑,本打算直接可以想vue2一樣使用粤策,執(zhí)行npm run build的時(shí)候卻發(fā)現(xiàn)報(bào)錯(cuò)了,不能這樣用瞳收,這就很奇怪了,而且現(xiàn)在3.0和vite還沒(méi)有廣泛使用厢汹,查文檔不是很清楚螟深。所以就想到了github的issues,果然有和我一樣需求的人問(wèn)了這個(gè)問(wèn)題烫葬。
那么就看 Evan You是怎么解釋的吧界弧,就是上面我引用的他的回復(fù),大家英語(yǔ)都挺好的搭综,我就不幫忙翻譯的垢箕,大概意思懂了就行。
下面就看兩種解決辦法吧:(以 VITE_APP_NAME為例)
// dotenv 需要單獨(dú)npm install
export default ({ mode }) => {
require('dotenv').config({ path: `./.env.${mode}` });
// now you can access config with process.env.{configName}
return defineConfig({
plugins: [vue()],
base:process.env.VITE_APP_NAME
})
}
第二種:
import { loadEnv } from 'vite'
export default ({ mode }) => {
return defineConfig({
plugins: [vue()],
base:loadEnv(mode, process.cwd()).VITE_APP_NAME
})
}
個(gè)人覺(jué)得第二種好一點(diǎn)吧兑巾,少安裝一個(gè)依賴(lài)条获,就這樣吧,有不妥的或者搞不定的可以聯(lián)系我蒋歌,加油各位帅掘!愿我們的代碼永遠(yuǎn)沒(méi)有bug!7茏恕!