posts - 148,  comments - 4,  views - 15万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

在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
        }
    }
}
复制代码

 

 

 


 
posted on   执候  阅读(60)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示