在Vite中编写插件需要遵循Vite的插件API

import type { Plugin } from 'vite';
export default function myPlugin(): Plugin {
return {
//插件生命周期钩子
resolveConfig(config) {
//在这里可以修改配置
return config;
},
config(config) {
//返回一个部分或者全新的配置对象
return config
},
configureServer(server) {
//在开发服务器启动时执行
},
configureDocs(docs){
//配置vite-plugin-vue-docs
},
loadConfigurationFile(filename) {
//读取并返回配置文件
},
transformIndexHtml(html) {
//转换index.html
return html;
},
transform(code, id, options){
return code
},
handleHotUpdate(ctx) {
//处理模块热更新
},
closeBundle() {
//打包结束时调用
}
}
}
新建一个vite文件夹
vite.config.ts里面引入编写
import vueNamePlugin from './vite/plugins/vue-name' export default defineConfig({ plugins: [ vueNamePlugin() ] })

出现这个报错只需要在tsconfig.node.json中加入以下即可

@vue/compiler-sfc 手动打包组件
import type { Plugin } from 'vite'
import { compileScript, parse } from '@vue/compiler-sfc'
export default function setupName(): Plugin {
return {
name: 'vite:plugin:vue:name',
enforce: 'pre',
transform(code, id) {
if (/.vue$/.test(id)) {
const { descriptor } = parse(code)
try {
const result = compileScript(descriptor, { id })
const name = result.attrs.name
const lang = result.attrs.lang
const inheritAttrs = result.attrs.inheritAttrs
const template = `
<script ${lang ? `lang=${lang}` : ''}>
export default {
${name ? `name:"${name}",` : ''}
${inheritAttrs ? `inheritAttrs: ${inheritAttrs !== 'false'},` : ''}
}
</script>
`
code += template
} catch (e) {
// TODO 忽略
}
}
return code
}
}
}
日常所遇,随手而记。
浙公网安备 33010602011771号