跳轉到內容

使用外掛

Vite 可以透過外掛進行擴充套件,這些外掛基於 Rollup 精心設計的外掛介面,並額外提供了一些 Vite 特有的選項。這意味著 Vite 使用者可以依賴成熟的 Rollup 外掛生態系統,同時也可以根據需要擴充套件開發伺服器和 SSR 功能。

新增外掛

要使用外掛,需要將其新增到專案的 devDependencies 中,幷包含在 vite.config.js 配置檔案中的 plugins 數組裡。例如,要為舊版瀏覽器提供支援,可以使用官方的 @vitejs/plugin-legacy

$ npm add -D @vitejs/plugin-legacy
vite.config.js
js
import 
legacy
from '@vitejs/plugin-legacy'
import {
defineConfig
} from 'vite'
export default
defineConfig
({
plugins
: [
legacy
({
targets
: ['defaults', 'not IE 11'],
}), ], })

plugins 也接受包含多個外掛的預設(presets)作為單個元素。這對於透過多個外掛實現複雜功能(例如框架整合)非常有用。陣列內部會被自動展平。

虛假值(Falsy)的外掛將被忽略,這可以用來方便地開啟或關閉外掛。

查詢外掛

注意

Vite 旨在為常見的 Web 開發模式提供開箱即用的支援。在尋找 Vite 或相容的 Rollup 外掛之前,請檢視 功能指南。在 Rollup 專案中需要外掛的許多場景,在 Vite 中已經涵蓋了。

請檢視 外掛部分 以獲取有關官方外掛的資訊。釋出到 npm 的社群外掛列在 Vite 外掛登錄檔 中。

強制外掛排序

為了與某些 Rollup 外掛相容,可能需要強制執行外掛的順序或僅在構建時應用。這應該是 Vite 外掛的實現細節。您可以使用 enforce 修飾符來強制外掛的位置:

  • pre:在 Vite 核心外掛之前呼叫外掛
  • default:在 Vite 核心外掛之後呼叫外掛
  • post:在 Vite 構建外掛之後呼叫外掛
vite.config.js
js
import 
image
from '@rollup/plugin-image'
import {
defineConfig
} from 'vite'
export default
defineConfig
({
plugins
: [
{ ...
image
(),
enforce
: 'pre',
}, ], })

請檢視 外掛 API 指南 獲取詳細資訊。

按需應用

預設情況下,外掛在開發伺服器(serve)和構建(build)時都會被呼叫。如果外掛只需要在開發或構建時有條件地應用,請使用 apply 屬性,將其設定為僅在 'build''serve' 時呼叫。

vite.config.js
js
import 
typescript2
from 'rollup-plugin-typescript2'
import {
defineConfig
} from 'vite'
export default
defineConfig
({
plugins
: [
{ ...
typescript2
(),
apply
: 'build',
}, ], })

構建外掛

檢視 外掛 API 指南 以獲取有關建立外掛的文件。