Skip to content

hsiangfeng/vue-custom-spec

Repository files navigation

Vue Custom Spec

在 Vue 單檔元件(SFC)中使用 <spec lang="md"> 標籤,讓 AI 開發更順暢

專案簡介

這是一個 Vite 插件範例專案,展示如何在 Vue 的單檔元件(Single File Component, SFC)中使用自訂區塊(Custom Block)<spec lang="md">,讓開發者能夠將規格文件直接寫在元件中,提升與 AI 工具(Claude Code、Gemini、Copilot 等)協作開發的效率。

背景與動機

AI 開發模式的挑戰

現在使用 AI 開發的常見模式包括:

  • SDD(Specification Driven Development,規格驅動開發):先撰寫規格文件,然後讓 AI 根據規格文件來產生程式碼
  • BDD(Behavior Driven Development,行為驅動開發):先撰寫行為描述,然後讓 AI 根據行為描述來產生程式碼
  • TDD(Test Driven Development,測試驅動開發):先撰寫測試案例,然後讓 AI 根據測試案例來產生程式碼

其中 SDD 是最多人使用的模式,但隨著專案成長,開發文件會變得越來越多:

  • *.spec.md - 專案規格文件
  • *.test.md - 測試案例文件
  • *.guide.md - 開發指南文件
  • *.task.md - 任務清單文件
  • README.md - 專案說明文件

這些文件需要不斷更新以跟程式碼保持一致,不僅增加維護成本,也會消耗 AI 的 Context Window(上下文視窗)。

解決方案

利用 Vue 的自訂區塊特性,我們可以將規格文件直接寫在元件中:

<script setup>
import { ref } from 'vue'

const message = ref('Hello World')
</script>

<template>
  <div>
    <h1 class="message">{{ message }}</h1>
  </div>
</template>

<style scoped>
.message {
  color: blue;
}
</style>

<spec lang="md">
- 這是一個簡單的 Vue 元件,顯示一個藍色的 "Hello World" 訊息。
- 使用了 Vue 3 的 Composition API 來定義響應式變數 `message`。
- 樣式使用了 scoped,確保樣式只作用於此元件。
- `message` 的文字顏色設定為藍色。
</spec>

優點

  • 集中管理:規格文件直接寫在元件檔案中,方便查看與維護,每個元件都有自己的規格,方便團隊協作與溝通
  • 上下文一致:AI 在生成程式碼時,可以直接參考元件內的規格,減少誤解
  • 減少文件數量:不需要額外維護多個規格文件,減少混亂
  • 節省 Context Window:將相關資訊集中在一個檔案中,減少 AI 需要處理的檔案數量

使用方式

Vite 版本

vite.config.js 中加入插件:

import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [
    vue(),
    {
      name: 'vue-spec-plugin',
      enforce: 'pre', // 在其他外掛程式之前執行
      transform(_code, id) {
        // 更精確的正則表達式匹配 .vue 檔案中的 spec 區塊
        if (/\.vue\?vue&type=spec(?:&|$)/.test(id)) {
          return {
            code: 'export default {};',
            map: null,
          }
        }
        // 明確回傳 null 表示不處理此檔案
        return null
      },
    },
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
})

Nuxt 版本

nuxt.config.ts 中加入插件:

export default defineNuxtConfig({
  vite: {
    plugins: [
      {
        name: 'vue-spec-plugin',
        enforce: 'pre', // 在其他外掛程式之前執行
        transform(_code, id) {
          // 更精確的正則表達式匹配 .vue 檔案中的 spec 區塊
          if (/\.vue\?vue&type=spec(?:&|$)/.test(id)) {
            return {
              code: 'export default {};',
              map: null,
            }
          }
          // 明確回傳 null 表示不處理此檔案
          return null
        },
      },
    ],
  },
})

專案安裝

npm install

開發模式

npm run dev

建置專案

npm run build

預覽建置結果

npm run preview

注意事項

  • 此方式僅適用於 .vue 檔案
  • 對於純 JS/TS 檔案,建議使用 JSDoc 或 TypeScript 的型別定義來描述規格
  • <spec> 區塊的內容不會被編譯到最終的程式碼中,僅用於開發時參考

參考資料

相關文章

延伸閱讀

授權

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published