Vite 8
Vite 8.x,來自 https://vite.dev/guide/。每個主張皆附有來源頁面。
如何導航
- 閱讀下方的快速規則。它們能捕捉最常見的錯誤。
- 根據表格開啟與任務相符的參考檔案。
- 對於
rollupOptions、esbuild或manualChunks,請先閱讀references/migration.md。
快速開始
// vite.config.ts
import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '') // 此處 process.env 中沒有 .env 檔案
return {
plugins: [react()],
server: { port: Number(env.PORT ?? 5173), strictPort: true },
build: {
rolldownOptions: { output: { /* Rolldown 選項,非 Rollup */ } },
},
}
})
{ "compilerOptions": { "types": ["vite/client"], "isolatedModules": true } }
- Node.js 20.19+ 或 22.12+。使用
npm create vite@latest my-app -- --template react-ts建立專案。https://vite.dev/guide/ - 腳本:
vite(開發,連接埠 5173)、vite build、vite preview(連接埠 4173,僅供本地檢查,絕非正式伺服器)。https://vite.dev/guide/cli , https://vite.dev/config/preview-options - Vite 從不進行型別檢查。請同時執行
tsc --noEmit。https://vite.dev/guide/features#transpile-only
快速規則
工具鏈與配置
- Rolldown 負責建構與預先打包相依套件。Oxc 負責轉換與壓縮 JavaScript,Lightning CSS 負責壓縮 CSS。https://vite.dev/guide/why#a-unified-toolchain , https://vite.dev/guide/migration#dependency-optimizer-now-uses-rolldown , https://vite.dev/guide/migration#javascript-transforms-by-oxc , https://vite.dev/guide/migration#css-minification-by-lightning-css
- 使用
build.rolldownOptions、worker.rolldownOptions、optimizeDeps.rolldownOptions和oxc。rollupOptions、esbuildOptions和esbuild鍵已被棄用。https://vite.dev/guide/migration#other-related-deprecations , https://vite.dev/guide/migration#javascript-transforms-by-oxc - 使用頂層
input選項宣告入口點。它是build.rolldownOptions.input、build.lib.entry和optimizeDeps.entries的預設值。https://vite.dev/config/shared-options#input - 程式碼分割透過
build.rolldownOptions.output.codeSplitting,而非manualChunks。https://vite.dev/guide/build#chunking-strategy tsconfig的target會被忽略:請設定build.target(預設為'baseline-widely-available')。Vite 不會添加 polyfill,請使用@vitejs/plugin-legacy。https://vite.dev/guide/features#target , https://vite.dev/config/build-options#build-target , https://vite.dev/guide/build#browser-compatibility- Oxc 無法降級原生的裝飾器(decorators)或混淆屬性。請添加 Babel 或 SWC,並過濾僅處理包含
@的檔案。https://vite.dev/guide/migration#javascript-transforms-by-oxc , https://vite.dev/guide/migration#javascript-minification-by-oxc - 從 CommonJS 的預設匯入(default import)現在可能回傳整個
module.exports(錯誤訊息為 "got: object"、"is not a function")。https://vite.dev/guide/migration#consistent-commonjs-interop , https://vite.dev/guide/troubleshooting#default-import-unexpectedly-returns-an-object
環境變數與模式
- 只有
VITE_開頭的變數會進入客戶端程式碼,且始終為字串型別,並會被內聯到打包結果中。絕對不要在裡面放置機密,也絕對不要設定envPrefix: ''。https://vite.dev/guide/env-and-mode#env-variables , https://vite.dev/config/shared-options#envprefix .env檔案在配置執行後才載入。在vite.config中,請使用loadEnv(mode, root, '')。https://vite.dev/config/#using-environment-variables-in-config- Shell 變數的優先順序高於
.env檔案。編輯.env後需要重新啟動。https://vite.dev/guide/env-and-mode#env-files --mode和NODE_ENV是獨立的:vite build --mode staging仍然是生產建構。https://vite.dev/guide/env-and-mode#node-env-and-modes- 請直接使用
import.meta.env.BASE_URL,中括號寫法不會被替換。https://vite.dev/guide/build#public-base-path
開發伺服器
- 絕不要設定
server.allowedHosts: true或server.cors: true:任何網站都可能讀取你的原始碼。https://vite.dev/config/server-options#server-allowedhosts , https://vite.dev/config/server-options#server-cors - 若連接埠已被佔用,除非設定了
strictPort: true,否則會自動移到下一個可用連接埠。https://vite.dev/config/server-options#server-port - WebSocket 設定位於
server.ws。server.hmr僅保留boolean | { overlay }。https://vite.dev/config/server-options#server-hmr - 在執行
npm link或編輯已連結的相依套件後,使用vite --force重新啟動。https://vite.dev/guide/troubleshooting#outdated-pre-bundled-deps-when-linking-to-a-local-package - 完全重新載入而非 HMR 可能由循環相依性引起(請執行
vite --debug hmr檢查)。https://vite.dev/guide/troubleshooting#a-full-reload-happens-instead-of-hmr
建構與部署
- 為 HTML 提供
Cache-Control: no-cache並在vite:preloadError事件重新載入,否則部署後舊頁面會失效。https://vite.dev/guide/build#load-error-handling import.meta.glob的引數必須是字面常數。動態import()必須以./、../或#開頭,並以檔案副檔名結尾:import(`./dir/${name}.js`)。https://vite.dev/guide/features#glob-import-caveats , https://vite.dev/guide/features#dynamic-import- 將 CSS 作為字串匯入:
import css from './a.css?inline'。不再支援對.css檔案的預設匯入。https://vite.dev/guide/features#disabling-css-injection-into-the-page - 函式庫模式會靜態替換
import.meta.env.*,但保持process.env.*不變。https://vite.dev/guide/build#library-mode
外掛、HMR、SSR
- 使用鉤子過濾器:
transform: { filter: { id: /\\.ext$/ }, handler },並在將非 JS 內容轉換為 JS 時回傳moduleType: 'js'。https://vite.dev/guide/api-plugin#hook-filters , https://vite.dev/guide/migration#module-type-support-and-auto-detection - 在鉤子中讀取
this.environment,而不是ssr標誌。hotUpdate是handleHotUpdate的環境感知對應方法,後者的棄用僅計劃在未來的主要版本中進行。https://vite.dev/guide/api-environment-plugins#accessing-the-current-environment-in-hooks , https://vite.dev/changes/hotupdate-hook configureServer的中間件會比 Vite 內建的中間件先執行。若要讓中間件在 Vite 內建中間件之後執行,請回傳一個函數。https://vite.dev/guide/api-plugin#configureserver- 請在
if (import.meta.hot)內部直接使用import.meta.hot.accept(。https://vite.dev/guide/api-hmr#hot-accept-cb - SSR 開發:設定
server.middlewareMode: true和appType: 'custom',使用server.environments.ssr.runner.import()載入入口點(ssrLoadModule計劃棄用)。https://vite.dev/guide/ssr#setting-up-the-dev-server , https://vite.dev/guide/api-environment-frameworks#runnabledevenvironment , https://vite.dev/changes/ssr-using-modulerunner vite build僅建構客戶端。vite build --app會建構所有環境。https://vite.dev/guide/api-environment-frameworks#environments-during-build
舊模式
| 舊寫法 | 當前寫法 |
|---|---|
build.rollupOptions | build.rolldownOptions |
esbuild: { jsx..., jsxInject } | oxc: { jsx: {...}, jsxInject } |
optimizeDeps.esbuildOptions | optimizeDeps.rolldownOptions |
output.manualChunks | output.codeSplitting |
server.hmr.port、clientPort | server.ws.port、clientPort |
build.polyfillModulePreload | build.modulePreload.polyfill |
import s from './a.css' | import s from './a.css?inline' |
import.meta.hot.decline()(無作用) | import.meta.hot.invalidate() |
server.ssrLoadModule(url) | environment.runner.import(url) |
handleHotUpdate + server.ws.send | hotUpdate + this.environment.hot.send |
參考檔案
| 檔案 | 閱讀時機 |
|---|---|
| references/migration.md | 從 Vite 7 遷移至 8:重新命名的選項、CommonJS 互通性、已移除的功能 |
| references/config-and-env.md | 配置、loadEnv、import.meta.env、模式、base |
| references/code-features.md | TypeScript、JSX、HTML、CSS、資產、import.meta.glob、動態匯入、Worker、WebAssembly |
| references/dev-server.md | 主機、連接埠、allowedHosts、CORS、代理、中間件模式、預覽 |
| references/dependencies-and-performance.md | 預先打包、optimizeDeps、連結的套件、開發速度 |
| references/build.md | 目標、rolldownOptions、程式碼分割、函式庫模式 |
| references/backend-integration-and-deploy.md | 後端整合、manifest、靜態託管 |
| references/ssr.md | SSR 開發伺服器、生產建構、外部化、外掛 |
| references/plugins.md | 外掛鉤子、過濾器、虛擬模組、順序 |
| references/hmr-and-javascript-api.md | import.meta.hot、自訂事件、createServer、build、preview |
| references/environment-api.md | environments 配置、this.environment、configEnvironment、每個環境的狀態 |
| references/environment-frameworks.md | builder.buildApp、ModuleRunner |
已閱讀頁面:SOURCES.md。