Skip to content

Vite 和 Rollup 插件开发

基础面 Rollup Plugin

Rollup 插件开发

插件是一个对象,具有属性构建钩子输出生成钩子中的一个或多个

typescript
export default function myRollupPlugin() {
  return {
    // 属性
    name: 'my-rollup-plugin',
    // 构建钩子
    // 写法1
    buildStart(options: InputOptions) {},
    // code即文件内容,id为文件绝对路径
    // type TransformResult = string | null | Partial<SourceDescription></SourceDescription>
    transform(code: string, id: string): TransformResult {}

    // 写法2
    buildStart: {
      order: 'pre', // post null
      handler(options: InputOptions) {},
    },
  }
}

扩展 Vite Plugin

Vite 插件 API

在 Rollup 插件基础上,扩展属性钩子

typescript
export default function myVitePlugin() {
  return {
    name: 'my-vite-plugin',
    enforce: 'pre', // 或 post
    apply: 'build', // 或 'serve'

    configureServer(server) { 
      server.middlewares.use((req, res, next) => {}) 
    }, 
    ..., 
  }
}

包发布约定

Rollup 插件

  • rollup-plugin-前缀
  • package.json中包含roll-pluginvite-plugin关键字

Vite 专属插件

  • vite-plugin-前缀
  • package.json中包含vite-plugin关键字
  • 在插件文档增加一部分关于为什么本插件是一个 Vite 专属插件的详细说明(如,本插件使用了 Vite 特有的插件钩子)
  • 如果插件只适用特定框架,带上框架前缀,如vite-plugin-vue-vite-plugin-react-