# 撰寫新程式碼 (/zh-Hant/docs/verdent-for-vscode/task-based-guides/writing-code)

> 使用 Verdent 撰寫新功能、元件與功能特性的指南



Verdent for VS Code 透過自然語言請求協助你撰寫新程式碼，無需特殊語法。描述你想建立的內容，Verdent 就會跨多個檔案建立可用於正式環境的實作，同時維持你專案的模式與慣例。

### 你將學到什麼 [#你將學到什麼]

* 使用自然語言提示詞請求新功能
* 跨多個檔案產生具有正確相依關係的程式碼
* 使用各種程式語言與框架
* 建構整個專案結構
* 透過對話式精修迭代產生的程式碼

### 先決條件 [#先決條件]

在使用 Verdent 撰寫程式碼之前：

* 已安裝 Verdent 擴充功能的 Visual Studio Code
* 具備可用點數的有效 Verdent 訂閱
* 已在 VS Code 開啟專案工作區（或用於建構的空目錄）

***

## 請求新功能 [#請求新功能]

Verdent 理解自然語言的功能請求，無需特殊指令或語法。只要在輸入框中描述你的需求即可。

**基本功能請求：**

從直接描述你需要什麼開始：

```
Create a UserProfile component that shows the user's avatar image, name as a heading, and email below it. Make the avatar circular.
```

```
Add a login form with email and password fields to the authentication page
```

```
Build a notification system that displays toast messages for success and error events
```

Verdent 會分析你的請求、檢視你的專案結構，並產生符合既有模式的程式碼，包括檔案組織、命名慣例、匯入風格與程式撰寫實務。

**詳細實作請求：**

若需要更多掌控，可明確指定技術需求：

```
Add a dark mode toggle to the settings page using React Context API. Store the theme preference in localStorage and apply CSS variables for light and dark themes across all components.
```

```
Create a POST /api/users/register endpoint that validates email format, password strength (min 8 chars, uppercase, number, special char), and checks for duplicate emails before creating the user in the database.
```

```
Implement pagination for the blog posts list with 10 posts per page. Add Previous/Next buttons and page number indicators. Update the URL query params (?page=2) and fetch data from /api/posts?page=X&limit=10.
```

你提供的上下文越多，實作就越貼近你的期望。

<Tabs>
  <Tab title="簡單請求">
    對於直接的功能，使用簡潔的描述：

    ```
    Add a search bar to the navigation
    ```

    ```
    Create a footer component with copyright and links
    ```

    Verdent 會根據你專案既有的程式碼模式做出合理的實作選擇。
  </Tab>

  <Tab title="使用 Plan Mode 的複雜請求">
    對於多檔案功能或架構決策，使用 **Plan Mode** 在執行前審查方法：

    **步驟 1：** 使用「Switch Mode」按鈕切換至 Plan Mode

    **步驟 2：** 提交你的功能請求：

    ```
    Add a search feature to the product catalog with filtering by category and price range
    ```

    **步驟 3：** Verdent 會建立一份詳細計畫，顯示：

    * 要建立的新檔案（搜尋元件、篩選 UI、API 端點）
    * 要修改的既有檔案（產品目錄頁面、路由、狀態管理）
    * 要新增的相依套件（若有）
    * 依邏輯順序排列的實作步驟

    **步驟 4：** Verdent 可能會詢問澄清問題：

    * 搜尋應為即時還是按鈕觸發？
    * 如何處理空結果？
    * 要包含哪些排序選項？

    **步驟 5：** 審查計畫並選擇你的下一步動作：

    * 選擇 **Edit** 進一步精修計畫
    * 選擇 **Start Building** 開始執行

    這種方法能在進行變更之前，確保你的期望與 Verdent 的實作一致。
  </Tab>
</Tabs>

<Tip>
  當功能影響多個檔案或需要架構決策時，使用 Plan Mode。你可以在執行前進行多輪計畫審查以精修方法。
</Tip>

***

## 透過 @-提及新增上下文 [#透過--提及新增上下文]

當你想要針對性地新增功能時，可引用特定檔案或元件：

```
@auth.js Add password reset functionality to this authentication module
```

```
@components/Dashboard.js Add a statistics widget showing user activity for the past 30 days
```

`@` 符號後接檔案路徑，會告訴 Verdent 在實作你的請求時聚焦於特定程式碼。這能確保新功能與既有實作無縫整合。

***

## 語言與框架支援 [#語言與框架支援]

Verdent 幾乎可用於任何程式語言，並理解程式碼語意、語法模式與各大主流生態系的常見框架，無需語言專用外掛。

<Tabs>
  <Tab title="卓越支援">
    具有出色成果與深入框架理解的語言：

    * **JavaScript & TypeScript** - React、Vue、Angular、Node.js、Next.js、現代 async/await 模式、元件分析
    * **Python** - Django、Flask、FastAPI、Pandas、NumPy、Jupyter notebooks、後端服務、資料分析
    * **Java/Kotlin** - Spring Boot、Hibernate、Maven/Gradle 生態系、企業級開發

    <CodeGroup>
      ```jsx "React Component"
      function UserProfile({ user }) {
        return (
          <div className="profile">
            <h1>{user.name}</h1>
            <p>{user.email}</p>
          </div>
        );
      }
      ```

      ```vue "Vue Component"
      <template>
        <div class="profile">
          <h1>{{ user.name }}</h1>
          <p>{{ user.email }}</p>
        </div>
      </template>

      <script setup>
      defineProps(['user']);
      </script>
      ```

      ```tsx "Angular Component"
      @Component({
        selector: 'user-profile',
        template: `
          <div class="profile">
            <h1>{{ user.name }}</h1>
            <p>{{ user.email }}</p>
          </div>
        `
      })
      export class UserProfileComponent {
        @Input() user!: User;
      }
      ```
    </CodeGroup>
  </Tab>

  <Tab title="強力支援">
    具備全面框架知識的其他語言：

    * **C++** - 記憶體管理、效能最佳化、系統程式設計
    * **Rust** - 記憶體安全模式、所有權概念、cargo 生態系
    * **Go** - 並行模式、微服務、CLI 工具
    * **C#** - .NET 生態系、LINQ 模式、非同步程式設計
    * **Ruby** - Rails 應用程式、腳本撰寫
    * **PHP** - Laravel、WordPress、Web 應用程式
    * **Swift/Objective-C** - iOS/macOS 開發
  </Tab>
</Tabs>

Verdent 也支援 Shell 腳本（Bash、Zsh）、SQL、HTML/CSS、Markdown、YAML、JSON 與設定語言。

#### 框架理解 [#框架理解]

除了語言之外，Verdent 也能辨識框架專屬的模式：

| 類別      | 框架與模式                                                                                    |
| ------- | ---------------------------------------------------------------------------------------- |
| **前端**  | React hooks、Redux、Context API、Vue Composition API、Angular 相依注入、Next.js server components |
| **後端**  | Express middleware、Django ORM、Spring Boot 微服務、FastAPI 非同步端點、Rails Active Record          |
| **測試**  | Jest、Pytest、JUnit、Mocha/Chai、Cypress、React Testing Library                               |
| **資料庫** | Prisma、TypeORM、Sequelize、SQLAlchemy、Hibernate、Mongoose                                   |

<Note>
  Verdent 會適應你的技術堆疊，而非要求特定語言或框架。無論使用何種程式語言，具有清晰關注點分離且組織良好的程式庫都能產生更好的結果。
</Note>

**為較不常見的語言進行最佳化：**

對於特殊框架或較不常見的語言，可透過以下方式改善結果：

* 提供展示你想遵循模式的程式碼範例
* 透過 @-提及納入既有程式庫的程式碼片段
* 使用 MCP（Model Context Protocol）伺服器注入語言專屬的上下文

***

## 多檔案程式碼產生 [#多檔案程式碼產生]

Verdent 在單次請求中建立多個協調一致的檔案，自動處理匯入、相依關係與跨檔案參照。

**範例：**

```
Create a UserDashboard component with a separate hooks file for data fetching, a styles file, a types file for TypeScript interfaces, and a test file
```

Verdent 會產生：

* `components/UserDashboard/UserDashboard.tsx` - 主元件
* `components/UserDashboard/useUserData.ts` - 自訂 hook
* `components/UserDashboard/UserDashboard.module.css` - 樣式
* `components/UserDashboard/types.ts` - TypeScript 介面
* `components/UserDashboard/UserDashboard.test.tsx` - 測試

所有檔案都包含彼此之間正確的匯入與連結。

**平行 vs. 循序產生：**

對於**鬆耦合的檔案**（獨立元件、各自獨立的模組、平行測試檔案），Verdent 可使用子代理平行撰寫多個檔案，提升速度與效率。

對於具有相互相依關係的**緊耦合檔案**（彼此匯入的檔案、共用型別、相依元件），Verdent 會循序撰寫以確保正確的相依管理與正確的匯入。

<Tip>
  對於多檔案功能，Verdent 會平行產生檔案，並自動在所有相關變更之間維持一致性。
</Tip>

***

## 產生樣板與建構結構 [#產生樣板與建構結構]

#### 樣板程式碼產生 [#樣板程式碼產生]

Verdent 透過理解你專案的既有模式來產生樣板，並建立遵循相同風格與結構的新程式碼：

```
Create a new ProductCard component with props for title, price, and image
```

```
Write an Express route handler for user registration with validation
```

```
Generate unit tests for the authentication service using Jest
```

Verdent 會分析你的程式庫以符合慣例（命名風格、匯入模式、資料夾結構），並產生能無縫整合的樣板，而非使用通用範本。

<Tip>
  使用 Plan Mode 在產生前審查候選樣板。Verdent 可詢問關於樣式方法、驗證規則或錯誤處理策略的澄清問題，以確保產生的程式碼符合你的確切需求。
</Tip>

#### 專案建構結構 [#專案建構結構]

Verdent 可建構整個專案結構，包含完整的資料夾階層、設定檔、相依套件與初始程式碼：

```
Create a new React application with TypeScript, React Router, Context API for state management, and Jest testing setup
```

Verdent 會產生完整的專案結構，包括 `package.json`、`tsconfig.json`、元件目錄、路由設定、context provider、測試檔案與版本控制設定（`.gitignore`、初始 commit）。

**建構結構的最佳實務：**

建構專案時使用 Plan Mode。Verdent 會：

1. 詢問關於偏好的澄清問題（樣式解決方案、元件結構、測試方法）
2. 提出含完整檔案結構與目錄佈局的詳細計畫
3. 讓你在建立前審查並精修建構結構
4. 產生專案並進行驗證，確保所有檔案都正確建立

對於複雜的建構結構，Verdent 可使用子代理將獨立的設定任務平行化（安裝相依套件、建立設定檔、設定資料庫 schema）。對於相互相依的檔案，它會維持循序撰寫以保留相依關係。

建構結構完成後，Verdent 可透過執行初始測試與建置指令來驗證設定，確保專案結構正確運作。

***

## 迭代產生的程式碼 [#迭代產生的程式碼]

Verdent 採用對話式工作流程，讓你在同一個聊天會話中透過自然語言的後續請求來精修產生的程式碼。

**基本迭代流程：**

1. Verdent 產生初始程式碼
2. 你審查輸出
3. 你提供回饋或請求變更
4. Verdent 根據你的回饋更新程式碼
5. 重複直到滿意為止

**迭代範例：**

```
Initial: Create a login form component
```

Verdent 產生一個基本表單。

```
Follow-up: Add email validation and show error messages below each field
```

Verdent 更新元件並加入驗證。

```
Follow-up: Style it with Tailwind CSS and add a loading state for the submit button
```

Verdent 精修樣式並新增載入行為。

**緊密的回饋循環：**

Verdent 在整個對話過程中維持上下文，讓你能夠：

* 請求增量變更而無需重複上下文
* 測試程式碼並回報問題讓 Verdent 修正
* 詢問關於實作選擇的「為什麼」問題
* 透過要求替代方案來嘗試不同的方法

<Tip>
  對於重大變更，描述哪裡有問題或你想要的不同之處，而非如何修正。Verdent 能分析問題並根據你的專案模式提出最佳解決方案。
</Tip>

***

## 最佳實務 [#最佳實務]

<Accordion title="依需要決定具體或概括程度">
  Verdent 理解各種詳細程度。當你有需求時提供技術細節，或使用概括描述讓 Verdent 根據你的專案模式做出明智選擇。
</Accordion>

<Accordion title="進行變更前先做探索">
  在請求新功能之前，先讓 Verdent 透過「分析資料庫 schema」或「解釋身份驗證流程」之類的問題理解你的程式庫。這能建立上下文並幫助 Verdent 提出更好的建議。
</Accordion>

<Accordion title="複雜或多檔案功能使用 Plan Mode">
  在執行前審查詳細的實作計畫。Verdent 會詢問澄清問題並建立結構化的方法。產生計畫後，選擇 **Edit** 進行精修或 **Start Building** 執行，確保在進行變更前達成一致。
</Accordion>

<Accordion title="運用 @-提及進行針對性整合">
  當你想要將變更與既有程式碼整合時引用特定檔案。這能確保新功能與目前的實作一致。
</Accordion>

<Accordion title="將複雜任務拆解為增量步驟">
  對於多步驟功能，採增量方式進行：先建立資料庫表，再建立 API 端點，然後是 UI 元件。這能維持清晰並讓你在每個步驟進行驗證。
</Accordion>

<Accordion title="提供的上下文越多，結果越貼近期望">
  納入關於技術選擇、設計偏好、驗證規則、錯誤處理策略或任何對你的實作至關重要的需求細節。
</Accordion>

***

## 另請參閱 [#另請參閱]

<CardGroup cols="2">
  <Card title="理解程式碼" icon="book" href="/docs/verdent-for-vscode/task-based-guides/understanding-code">
    了解如何使用 Verdent 探索與分析既有程式庫
  </Card>

  <Card title="測試與除錯" icon="bug" href="/docs/verdent-for-vscode/task-based-guides/testing-debugging">
    在 AI 協助下產生全面的測試並對問題進行除錯
  </Card>
</CardGroup>
