Vite 可以使用插件进行扩展,这得益于 Rollup 优秀的插件接口设计和一部分 Vite 独有的额外选项。
unplugin-vue-componentsVue 的按需组件自动导入。github地址
内置了大多数常见UI库解析器。以 Ant Design Vue 为例。
pnpm add unplugin-vue-components -D
// vite.config.js
import { defineConfig } from 'vite'
import Components from 'unplugin-vue-components/vite'
import {AntDesignVueResolver
} from 'unplugin-vue-components/resolvers'export default defineConfig({plugins: [Components({resolvers: [AntDesignVueResolver()]})]
})
unplugin-auto-import自动导入 Composition API。github地址
pnpm add unplugin-auto-import -D
// vite.config.js
import { defineConfig } from 'vite'
import autoImport from 'unplugin-auto-import/vite'export default defineConfig({plugins: [autoImport({imports: ['vue','vue-router','pinia'],dts: false})]
})
使用前:
import { computed, ref } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2)
使用后:
const count = ref(0)
const doubled = computed(() => count.value * 2)
rollup-plugin-visualizer打包分析插件。
pnpm add rollup-plugin-visualizer -D
// vite.config.js
import { defineConfig } from 'vite'
import { visualizer } from 'rollup-plugin-visualizer'export default defineConfig({plugins: [visualizer()]
})
打包后,会在根目录下生成一个 stats.html文件,用浏览器打开后,如下图:

vite-plugin-compression使用 gzip 或 brotli 压缩资源。github地址
pnpm add vite-plugin-compression -D
// vite.config.js
import { defineConfig } from 'vite'
import compression from 'vite-plugin-compression'export default defineConfig({plugins: [// gz格式compression({threshold: 1024 * 500, // 体积大于 threshold 才会被压缩,单位 bext: '.gz', // 压缩文件格式deleteOriginFile: false // 是否删除源文件})// br格式// compression({// threshold: 1024 * 500, // 体积大于 threshold 才会被压缩,单位 b// ext: '.br',// algorithm: 'brotliCompress',// deleteOriginFile: false// })]
})
| params | type | default | default |
|---|---|---|---|
| verbose | boolean | true | Whether to output the compressed result in the console |
| filter | RegExp or (file: string) => boolean | DefaultFilter | Specify which resources are not compressed |
| disable | boolean | false | Whether to disable |
| threshold | number | 1025 | It will be compressed if the volume is larger than threshold, the unit is b |
| algorithm | string | gzip | Compression algorithm, optional [‘gzip’,‘brotliCompress’ ,‘deflate’,‘deflateRaw’] |
| ext | string | .gz | Suffix of the generated compressed package |
| compressionOptions | object | - | The parameters of the corresponding compression algorithm |
| deleteOriginFile | boolean | - | Whether to delete source files after compression |