最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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();
});

九、最佳實踐

  1. 命名規(guī)范:使用 vite-plugin- 前綴
  2. TypeScript:使用 TS 開發(fā),提供類型
  3. 文檔:完善的 README
  4. 測試:提供單元測試
  5. 兼容性:考慮不同 Vite 版本

到此這篇關于Vite Plugin 開發(fā)完全指南的文章就介紹到這了,更多相關Vite Plugin 開發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

湟源县| 长子县| 永登县| 象州县| 哈尔滨市| 新平| 玛沁县| 宁晋县| 环江| 屏山县| 个旧市| 佛山市| 蒲江县| 岱山县| 南和县| 宝丰县| 长治县| 冀州市| 沅陵县| 鹤岗市| 石家庄市| 桂阳县| 昂仁县| 赤城县| 南澳县| 曲沃县| 东乡族自治县| 广宗县| 乌兰察布市| 泾川县| 瑞金市| 贞丰县| 旬阳县| 陵川县| 恭城| 稻城县| 青州市| 溧水县| 太谷县| 丹棱县| 视频|