Vite Plugin 開發(fā)完全指南
更新時間:2026年05月25日 09:18:32 作者:兆子龍
本篇文章詳細介紹了Vite插件開發(fā),涵蓋VitePlugin基礎使用、核心鉤子詳解、Rollup環(huán)插件應用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
一、第一個 Vite Plugin
1.1 創(chuàng)建基礎 Plugin
// plugins/vite-plugin-example.js
export default function examplePlugin() {
return {
name: 'vite-plugin-example',
config(config) {
console.log('config hook');
return {
define: {
__PLUGIN_VERSION__: '"1.0.0"'
}
};
},
configResolved(config) {
console.log('configResolved hook');
},
transform(code, id) {
console.log('transform:', id);
return code;
}
};
}
1.2 在 Vite 配置中使用
// vite.config.js
import { defineConfig } from 'vite';
import examplePlugin from './plugins/vite-plugin-example';
export default defineConfig({
plugins: [
examplePlugin()
]
});
二、核心鉤子詳解
2.1 config 和 configResolved
export default function configPlugin() {
return {
name: 'config-plugin',
config(config, { command, mode }) {
console.log('Command:', command); // 'serve' or 'build'
console.log('Mode:', mode); // 'development' or 'production'
// 修改配置
return {
server: {
port: 3000
},
build: {
outDir: 'dist'
}
};
},
configResolved(config) {
// 讀取最終配置
console.log('Final config:', config);
}
};
}
2.2 configureServer 開發(fā)服務器
export default function devServerPlugin() {
return {
name: 'dev-server-plugin',
configureServer(server) {
// 添加中間件
server.middlewares.use((req, res, next) => {
console.log('Request:', req.url);
next();
});
// 自定義路由
server.middlewares.use('/api/hello', (req, res) => {
res.end('Hello from Vite Plugin!');
});
// 監(jiān)聽 WebSocket 事件
server.ws.on('connection', (ws) => {
ws.send('Welcome!');
});
}
};
}
2.3 transformIndexHtml 轉(zhuǎn)換 HTML
export default function htmlPlugin() {
return {
name: 'html-plugin',
transformIndexHtml(html) {
return html.replace(
'<head>',
`<head>
<meta name="plugin-version" content="1.0.0">
`
);
}
// 或者返回對象
transformIndexHtml(html) {
return {
html,
tags: [
{
tag: 'script',
attrs: { src: '/custom-script.js' },
injectTo: 'head'
}
]
};
}
};
}
三、Rollup 鉤子在 Vite 中的應用
3.1 resolveId 解析模塊
export default function resolvePlugin() {
return {
name: 'resolve-plugin',
resolveId(source, importer) {
if (source === 'virtual:my-module') {
// 標記為虛擬模塊
return '\0virtual:my-module';
}
return null; // 讓其他插件處理
}
};
}
3.2 load 加載模塊
export default function loadPlugin() {
return {
name: 'load-plugin',
load(id) {
if (id === '\0virtual:my-module') {
return `
export const message = 'Hello from virtual module!';
export const version = '1.0.0';
`;
}
return null;
}
};
}
3.3 transform 轉(zhuǎn)換代碼
export default function transformPlugin() {
return {
name: 'transform-plugin',
transform(code, id) {
// 只處理 .js 文件
if (!id.endsWith('.js')) return;
// 簡單的代碼轉(zhuǎn)換
const transformedCode = code.replace(
/console\.log\(/g,
'console.log("[Plugin] "'
);
return {
code: transformedCode,
map: null // sourcemap
};
}
};
}
四、實戰(zhàn)案例一:虛擬模塊
4.1 創(chuàng)建虛擬模塊 Plugin
// plugins/vite-plugin-virtual.js
export default function virtualModulePlugin() {
const virtualModuleId = 'virtual:env-info';
const resolvedVirtualModuleId = '\0' + virtualModuleId;
return {
name: 'vite-plugin-virtual',
resolveId(id) {
if (id === virtualModuleId) {
return resolvedVirtualModuleId;
}
},
load(id) {
if (id === resolvedVirtualModuleId) {
return `
export const NODE_ENV = '${process.env.NODE_ENV || 'development'}';
export const VERSION = '${process.env.npm_package_version || '1.0.0'}';
export const BUILD_TIME = '${new Date().toISOString()}';
`;
}
}
};
}
4.2 使用虛擬模塊
// src/main.js
import { NODE_ENV, VERSION, BUILD_TIME } from 'virtual:env-info';
console.log('Environment:', NODE_ENV);
console.log('Version:', VERSION);
console.log('Build Time:', BUILD_TIME);
五、實戰(zhàn)案例二:處理自定義文件
5.1 處理 .yaml 文件
// plugins/vite-plugin-yaml.js
import yaml from 'js-yaml';
export default function yamlPlugin() {
return {
name: 'vite-plugin-yaml',
transform(code, id) {
if (id.endsWith('.yaml') || id.endsWith('.yml')) {
try {
const data = yaml.load(code);
return {
code: `export default ${JSON.stringify(data)};`
};
} catch (e) {
this.error(e.message);
}
}
}
};
}
5.2 使用 YAML 文件
# config.yaml app: name: My App version: 1.0.0 database: host: localhost port: 5432
import config from './config.yaml'; console.log(config.app.name); console.log(config.database.port);
六、實戰(zhàn)案例三:熱更新處理
6.1 自定義 HMR
// plugins/vite-plugin-hmr.js
export default function hmrPlugin() {
return {
name: 'vite-plugin-hmr',
handleHotUpdate({ file, server, modules }) {
console.log('File changed:', file);
// 自定義更新邏輯
if (file.endsWith('.special')) {
server.ws.send({
type: 'custom',
event: 'special-update',
data: { file }
});
return []; // 不觸發(fā)默認更新
}
return modules; // 默認行為
}
};
}
6.2 客戶端接收 HMR
// src/hmr-client.js
if (import.meta.hot) {
import.meta.hot.on('special-update', (data) => {
console.log('Special update:', data);
// 自定義更新處理
});
}
七、插件開發(fā)技巧
7.1 區(qū)分開發(fā)與生產(chǎn)環(huán)境
export default function envPlugin() {
let isDev;
return {
name: 'env-plugin',
configResolved(config) {
isDev = config.command === 'serve';
},
transform(code, id) {
if (isDev) {
// 開發(fā)環(huán)境邏輯
return code + '\nconsole.log("Dev only");';
} else {
// 生產(chǎn)環(huán)境邏輯
return code;
}
}
};
}
7.2 插件排序
// vite.config.js
export default defineConfig({
plugins: [
pluginA(), // 先執(zhí)行
pluginB(), // 后執(zhí)行
]
});
// 使用 enforce
export default function plugin() {
return {
name: 'my-plugin',
enforce: 'pre', // 'pre' | 'post' | undefined
};
}
八、調(diào)試與測試
8.1 調(diào)試 Plugin
// 使用 debug
import createDebug from 'debug';
const debug = createDebug('vite-plugin-example');
export default function debugPlugin() {
return {
name: 'debug-plugin',
transform(code, id) {
debug('Transforming:', id);
return code;
}
};
}
8.2 測試 Plugin
// test/plugin.test.js
import { createServer } from 'vite';
import myPlugin from '../index.js';
test('plugin works', async () => {
const server = await createServer({
plugins: [myPlugin()]
});
// 測試邏輯
await server.close();
});
九、最佳實踐
- 命名規(guī)范:使用
vite-plugin-前綴 - TypeScript:使用 TS 開發(fā),提供類型
- 文檔:完善的 README
- 測試:提供單元測試
- 兼容性:考慮不同 Vite 版本
到此這篇關于Vite Plugin 開發(fā)完全指南的文章就介紹到這了,更多相關Vite Plugin 開發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
- Vue3+Vite項目中引入pinia和pinia-plugin-persistedstate的方法代碼
- Vite使用unplugin-auto-import實現(xiàn)vue3中的自動導入
- 3分鐘搞定vite項目(vue/react)使用vite-plugin-pwa配置為pwa應用
- vue3項目導入異常Error:@vitejs/PLUGIN-vue?requires?vue?(>=3.2.13)解決辦法
- vue3+vite使用vite-plugin-svg-icons插件顯示本地svg圖標的方法
- Vite處理html模板插件之vite-plugin-html插件使用
- 解決vue3+vite配置unplugin-vue-component找不到Vant組件
- vite打包優(yōu)化vite-plugin-compression的使用示例詳解
- vue3+vite多項目多模塊打包(基于vite-plugin-html插件)
- 在?Vite項目中使用插件?@rollup/plugin-inject?注入全局?jQuery的過程詳解
- vue3+vite引入插件unplugin-auto-import的方法
相關文章
vue+el-select?多數(shù)據(jù)分頁搜索組件的實現(xiàn)
本文主要介紹了vue+el-select?多數(shù)據(jù)分頁搜索組件的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-12-12
vue如何使用watch監(jiān)聽指定數(shù)據(jù)的變化
這篇文章主要介紹了vue如何使用watch監(jiān)聽指定數(shù)據(jù)的變化,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
解決Vue+Electron下Vuex的Dispatch沒有效果問題
這篇文章主要介紹了Vue+Electron下Vuex的Dispatch沒有效果的解決方案 ,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-05-05

