跳转至

第五章:插件系统

插件概念

Vite 插件

// 插件结构
const myPlugin = {
  name: 'my-plugin',

  // 服务器启动时
  configureServer(server) {
    // ...
  },

  // 构建开始时
  buildStart() {
    // ...
  },

  // 转换模块
  transform(code, id) {
    // ...
  },

  // 构建结束时
  buildEnd() {
    // ...
  }
}

常用插件

Vue 插件

import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

export default defineConfig({
  plugins: [
    vue(),
    vueJsx()
  ]
})

React 插件

import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()]
})

其他插件

import { visualizer } from 'rollup-plugin-visualizer'
import viteCompression from 'vite-plugin-compression'

export default defineConfig({
  plugins: [
    // 打包分析
    visualizer(),
    // Gzip 压缩
    viteCompression()
  ]
})

自定义插件

示例

const myPlugin = {
  name: 'my-plugin',

  transform(code, id) {
    if (id.endsWith('.md')) {
      return {
        code: `export default ${JSON.stringify(code)}`,
        map: null
      }
    }
  }
}

export default defineConfig({
  plugins: [myPlugin]
})

小结

插件系统要点:

  • 插件结构:name、configureServer、transform 等
  • 常用插件:vue、react、visualizer
  • 自定义插件:transform 转换代码

下一章我们将学习 Vue 集成。