posts - 148,  comments - 4,  views - 15万
< 2025年2月 >
26 27 28 29 30 31 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 1
2 3 4 5 6 7 8

在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   执候  阅读(55)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
点击右上角即可分享
微信分享提示