项目使用vite构建打包时, 可以方便的拓展自定义的能力, 其中一个就是插件机制, 插件的使用几乎在所有的vite项目中都会使用到. 例如我们使用 vite 来创建一个简单的 react 工程
npm init vite@latest
创建完成后, 打开 vite.config.ts 文件后我们看到其中就使用了 @vitejs/plugin-react 插件
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
})
在学习了 Vite 的插件机制后,我们接下来利用已掌握的Vite插件开发的基本知识来实战Vite插件的开发工作。
最简单的插件
Vite 插件与 Rollup 插件结构类似,为一个name和各种插件 Hook 的对象:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// 一个最简单的插件
const myPlugin = {
name: 'vite-plugin-xxx',
load(filepath) {
console.log('load', filepath)
}
}
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), myPlugin],
})
vitejs官方提供的插件都是发布在 vite 命名空间下,以 @vitejs/plugin- 开头的.
如果要开发一个我们自己的vite插件,建议命名以vite-plugin-开头。通常为了插件的灵活性,要考虑外部传参,我们不会直接写一个对象,而是实现一个返回插件对象的工厂函数,如下代码所示:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
function myPlugin(options) {
console.log(options)
return {
name: 'vite-plugin-xxx',
load(filepath) {
// 这里可以访问外部传入进来的配置参数
console.log(options, filepath)
}
}
}
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), myPlugin({})],
});