在 Vue 單檔元件(SFC)中使用
<spec lang="md">標籤,讓 AI 開發更順暢
這是一個 Vite 插件範例專案,展示如何在 Vue 的單檔元件(Single File Component, SFC)中使用自訂區塊(Custom Block)<spec lang="md">,讓開發者能夠將規格文件直接寫在元件中,提升與 AI 工具(Claude Code、Gemini、Copilot 等)協作開發的效率。
現在使用 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.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.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 installnpm run devnpm run buildnpm run preview- 此方式僅適用於
.vue檔案 - 對於純 JS/TS 檔案,建議使用 JSDoc 或 TypeScript 的型別定義來描述規格
<spec>區塊的內容不會被編譯到最終的程式碼中,僅用於開發時參考
- 用 <spec lang="md"> 標籤在 Vue 中舒服的使用 SFC 搭配 AI 開發 - 本專案的完整介紹文章
- Vue SFC のカスタムブロックと AI 駆動開発の相性が良い理由
- Vue のカスタムブロックで「気軽に」始める仕様駆動開発のススメ
- Vue SFC Custom Block Integrations
MIT