写过Vue3的肯定用过VueSetupExtend这个插件吧,但是它的缺陷你知道吗

手写一个 VueSetupExtend 插件

目的

在 Vue 3 项目中,为组件定义 name 是一件频繁却略显繁琐的事情。Vue 官方提供了两种主流方式:

定义方式一:使用 defineComponent

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'MyComponent',
  setup() {
    // ...
  }
})
</script>

定义方式二:在 <script setup> 中使用 defineOptions

<script setup lang="ts">
defineOptions({
  name: 'MyComponent'
})
</script>

这两种方式虽然标准,但都有点“啰嗦”或对新手不够友好。

于是,有开发者提出了一种更“语义化”也更简单的方式 —— 直接通过 <script setup> 标签的 name 属性来定义组件名

<script setup lang="ts" name="MyComponent">
</script>

这种写法直观、简洁,也非常适合团队规范化开发。

VueSetupExtend 插件的目标

VueSetupExtend 插件就是为了解析 <script setup name="..."> 中的 name 属性,并在编译前自动转换为标准的 Vue 组件定义,从而实现自动注入组件名称。

源码讲解

import { parse, compileScript } from '@vue/compiler-sfc'
import MagicString from 'magic-string'

export function supportScriptName(code: string, id: string) {
  let s: MagicString | undefined
  const str = () => s || (s = new MagicString(code))
  const { descriptor } = parse(code)
  if (!descriptor.script && descriptor.scriptSetup) {
    const result = compileScript(descriptor, { id })
    const name = result.attrs.name
    const lang = result.attrs.lang
    if (name) {
      str().appendLeft(
        0,
        `<script ${lang ? `lang="${lang}"` : ''}>
import { defineComponent } from 'vue'
export default defineComponent({
  name: '${name}',
})
</script>\n`,
      )
    }
    return {
      map: str().generateMap(),
      code: str().toString(),
    }
  } else {
    return null
  }
}

代码简单,就是解析一下如果有script或者scriptSetup就添加一个组件name属性声明的script标签。

问题:当 <script setup> 是空时,@vue/compiler-sfc 无法解析 name

Vue 官方的 @vue/compiler-sfc 在解析 .vue 文件时,如果 <script setup> 为空,它将忽略这个块,导致我们拿不到 name 属性,也无法通过 compileScript 提取它。

所以需要我们手动“补救”:注入一个占位符,如注释 // __placeholder__,强制解析器识别这一段 script,从而达到预期目的。

但问题也来了 —— 这个插件功能非常简单,真的需要引入 @vue/compiler-sfc 吗?

答案:不需要,完全可以用更轻量的方式实现

这里我们探讨两种方案:

方案一:正则方式(不推荐)

const match = code.match(/<script\s+setup[^>]*name\s*=\s*["']([^"']+)["']/i)
const name = match?.[1]
然后将其插入一个常规的 <script>块:
const injection = `
<script>
import { defineComponent } from 'vue'
export default defineComponent({
  name: '${name}'
})
</script>
`
code = injection + '\n' + code

缺点:

  • 容易受格式影响(如属性换行、属性间多个空格等)
  • 对复杂 HTML 不稳健

方案二:使用 htmlparser2 提取 name(推荐)

相比正则,htmlparser2 是一个容错性强、灵活可靠的 HTML 解析器,能准确识别空的 <script setup> 块及其属性。

安装依赖

npm install htmlparser2

核心实现代码

import { parseDocument } from 'htmlparser2'
import { Element, Text } from 'domhandler'

function extractNameFromScriptSetup(code: string): string | null {
  const doc = parseDocument(code)

  for (const node of doc.childNodes) {
    if (
      node instanceof Element &&
      node.name === 'script' &&
      'setup' in node.attribs
    ) {
      return node.attribs.name || null
    }
  }

  return null
}

function injectComponentName(code: string): string {
  const name = extractNameFromScriptSetup(code)
  if (!name) return code

  const injection = `
<script>
import { defineComponent } from 'vue'
export default defineComponent({
  name: '${name}'
})
</script>
`
  return injection + '\n' + code
}

可运行源码

// plugins/vueSetupExtend.ts
import { Plugin } from 'vite'
import { parseDocument } from 'htmlparser2'
import { Element } from 'domhandler'
import MagicString from 'magic-string'

function extractNameFromScriptSetup(code: string): { name: string; lang?: string } | null {
  const doc = parseDocument(code)

  for (const node of doc.childNodes) {
    if (
      node instanceof Element &&
      node.name === 'script' &&
      'setup' in node.attribs
    ) {
      const name = node.attribs.name
      const lang = node.attribs.lang
      if (name) {
        return { name, lang }
      }
    }
  }

  return null
}

function injectComponentName(code: string, name: string, lang?: string): { code: string; map: any } {
  const s = new MagicString(code)

  const injectScript = `<script${lang ? ` lang="${lang}"` : ''}>
import { defineComponent } from 'vue'
export default defineComponent({
  name: '${name}'
})
</script>\n\n`

  s.prepend(injectScript)

  return {
    code: s.toString(),
    map: s.generateMap({ hires: true }),
  }
}

export default function VueSetupExtend(): Plugin {
  return {
    name: 'vite:vue-setup-extend',
    enforce: 'pre',

    transform(code, id) {
      if (!id.endsWith('.vue')) return

      const nameInfo = extractNameFromScriptSetup(code)
      if (!nameInfo) return

      const { name, lang } = nameInfo
      return injectComponentName(code, name, lang)
    },
  }
}

测试代码

<script setup lang="ts" name="Paaaa">

</script>

<template>
  <div>
    测试
  </div>
</template>

<style scoped lang='scss' >

![image.png](https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/4a44a4bac19749469f7e31fe435facb6~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5Yqg6L295LitMzYx:q75.awebp?rk3s=f64ab15b&x-expires=1749036615&x-signature=fK2JJ%2FpBu87ZVBPj1OmVQWc4eas%3D)
</style>

至于为什么要写这个插件,因为动态路由具有keeplive缓存选项的时候,需要频繁的定义name属性。

原文链接:https://juejin.cn/post/7509377620317028386

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值