設定 Vite
當從命令列執行 vite
時,Vite 會自動嘗試解析在專案根目錄中名為 vite.config.js
的設定檔(也支援其他 JS 和 TS 擴充功能)。
最基本的設定檔看起來像這樣
// vite.config.js
export default {
// config options
}
請注意,即使專案未使用原生 Node ESM,例如在 package.json
中使用 type: "module"
,Vite 也支援在設定檔中使用 ES 模組語法。在這種情況下,設定檔會在載入之前自動預處理。
您也可以使用 --config
CLI 選項(相對於 cwd
解析)明確指定要使用的設定檔
vite --config my-config.js
設定智能感知
由於 Vite 附帶 TypeScript 類型定義,您可以使用 jsdoc 類型提示來利用 IDE 的智能感知功能
/** @type {import('vite').UserConfig} */
export default {
// ...
}
或者,您可以使用 defineConfig
輔助函式,它應該提供智能感知,而無需 jsdoc 註解
import { defineConfig } from 'vite'
export default defineConfig({
// ...
})
Vite 也支援 TypeScript 設定檔。 您可以使用帶有上述 defineConfig
輔助函式的 vite.config.ts
,或使用 satisfies
運算子
import type { UserConfig } from 'vite'
export default {
// ...
} satisfies UserConfig
條件設定
如果設定需要根據命令(serve
或 build
)、正在使用的模式、是否為 SSR 建置 (isSsrBuild
) 或是否正在預覽建置 (isPreview
) 來有條件地決定選項,則它可以改為匯出一個函式
export default defineConfig(({ command, mode, isSsrBuild, isPreview }) => {
if (command === 'serve') {
return {
// dev specific config
}
} else {
// command === 'build'
return {
// build specific config
}
}
})
重要的是要注意,在 Vite 的 API 中,command
的值在開發期間為 serve
(在 CLI 中,vite
、vite dev
和 vite serve
是別名),而在為生產建置時為 build
(vite build
)。
isSsrBuild
和 isPreview
是額外的可選標誌,分別用於區分 build
和 serve
命令的種類。 某些載入 Vite 設定的工具可能不支援這些標誌,並且會改為傳遞 undefined
。 因此,建議使用與 true
和 false
的顯式比較。
異步設定
如果設定需要呼叫異步函式,則可以改為匯出異步函式。 而且這個異步函式也可以通過 defineConfig
傳遞,以獲得更好的智能感知支援
export default defineConfig(async ({ command, mode }) => {
const data = await asyncFunction()
return {
// vite config
}
})
在設定中使用環境變數
環境變數可以像往常一樣從 process.env
中取得。
請注意,Vite 預設不會載入 .env
檔案,因為要載入的檔案只能在評估 Vite 設定後才能確定,例如,root
和 envDir
選項會影響載入行為。但是,如果需要,您可以使用匯出的 loadEnv
輔助函式來載入特定的 .env
檔案。
import { defineConfig, loadEnv } from 'vite'
export default defineConfig(({ mode }) => {
// Load env file based on `mode` in the current working directory.
// Set the third parameter to '' to load all env regardless of the
// `VITE_` prefix.
const env = loadEnv(mode, process.cwd(), '')
return {
// vite config
define: {
__APP_ENV__: JSON.stringify(env.APP_ENV),
},
}
})