vite插件开发

4

简单示例

import type { Plugin } from 'vite'

export default function myPlugin(): Plugin {
  const pluginName = 'my-plugin-demo'

  return {
    name: pluginName,

    configResolved(config) {
      console.log(`[${pluginName}] config resolved. mode: ${config.mode}, root: ${config.root}`)
    },

    buildStart() {
      console.log(`[${pluginName}] build start`)
    },

    closeBundle() {
      console.log(`[${pluginName}] build finished`)
    },

    handleHotUpdate(ctx) {
      console.log(`[${pluginName}] HMR: ${ctx.file}`)
    },
  }
} 

钩子说明

vite专属钩子

函数

作用

config(config, env)

修改 Vite 配置(在解析之前执行)

configResolved(resolvedConfig)

获取最终解析好的配置(只读)

configureServer(server)

开发服务器启动时调用,可用来注册中间件等

transformIndexHtml(html, ctx)

转换 index.html(支持注入标签、修改内容)

handleHotUpdate(ctx)

处理热更新逻辑(HMR)

enforce

决定插件执行顺序:pre → 默认 → post

apply

限制插件运行环境(开发/构建)

集成rolup的钩子

函数

作用

options(options)

读取/修改 Rollup 配置

buildStart(options)

构建开始时执行

resolveId(source, importer, options)

自定义模块解析

load(id, options)

自定义模块加载

transform(code, id, options)

转换源码

buildEnd(err)

构建结束

closeBundle()

整个构建流程完成(适合做收尾清理)

参考

常见或者好用的插件可以参考: https://github.com/vitejs/awesome-vite#plugins