跳至主要內容
tutorial openclaw claude-code skills development

實戰指南:用 Claude Code 開發 OpenClaw Skills

一步步教學:如何使用 Claude Code 的高效開發流程,為 OpenClaw 創建強大的 Skills。從專案設置到測試部署,完整的開發者指南。

2026年2月5日 9 分鐘閱讀 作者:Claude World

前言:為何結合 Claude Code 與 OpenClaw?

OpenClaw 提供強大的 Agent 平台,但開發 Skills 需要時間。 Claude Code 提供高效的 AI 輔助開發體驗。

兩者結合 = 更快、更好的 Skills 開發流程

這篇文章將帶你完成:

  1. ✅ 環境設置
  2. ✅ 創建第一個 Skill
  3. ✅ 測試與除錯
  4. ✅ 部署與發布
  5. ✅ 最佳實踐

第一步:準備開發環境

1.1 安裝必要工具

# 安裝 Node.js (推薦 20+)
nvm install 20
nvm use 20

# 安裝 Claude Code CLI
npm install -g @anthropic-ai/claude-code

# 安裝 pnpm(OpenClaw 使用)
npm install -g pnpm

1.2 Clone OpenClaw 專案

# Fork OpenClaw 到你的 GitHub
# 然後 clone 你的 fork

git clone https://github.com/YOUR_USERNAME/openclaw.git
cd openclaw

# 安裝依賴
pnpm install

# 設置開發環境
cp .env.example .env
# 編輯 .env,添加必要的 API keys

1.3 設置 Git Hooks

# OpenClaw 使用 Git hooks 確保代碼品質
./scripts/setup-git-hooks.js

第二步:用 Claude Code 創建 Skill

2.1 使用 skill-creator 快速開始

# 在 OpenClaw 根目錄
claude -p "/skill-creator"

# Claude Code 會引導你:
# 1. Skill 名稱
# 2. 功能描述
# 3. 需要的工具
# 4. 觸發條件

互動範例

🤖 請描述你想創建的 Skill:

💬 我想創建一個 Skill,可以自動分析 GitHub repo 的技術棧,
   並生成視覺化的報告。

🤖 正在分析需求...
   建議技能名稱:tech-stack-analyzer
   建議工具:
   - GitHub API (獲取 repo 資訊)
   - Parser (分析 package.json/requirements.txt)
   - Report Generator (生成報告)

   確認生成?[Y/n]

2.2 手動創建 Skill 結構

cd skills
mkdir tech-stack-analyzer
cd tech-stack-analyzer

使用 Claude Code 生成骨架:

claude -p "
創建 OpenClaw skill 結構:

skill: tech-stack-analyzer
description: 分析 GitHub repo 技術棧並生成報告
tools:
  - fetch-repo-info
  - analyze-dependencies
  - generate-report

請生成完整的 skill.ts 和 manifest.json
"

第三步:實現 Skill 核心功能

3.1 定義 Skill Manifest

skills/tech-stack-analyzer/manifest.json

{
  "name": "tech-stack-analyzer",
  "version": "1.0.0",
  "description": "分析 GitHub repo 技術棧並生成可視化報告",
  "author": "Your Name <your.email@example.com>",
  "license": "MIT",
  "skills": {
    "analyze_repo": {
      "description": "分析指定 GitHub repo 的技術棧",
      "parameters": {
        "owner": {
          "type": "string",
          "description": "Repo owner (username or org)",
          "required": true
        },
        "repo": {
          "type": "string",
          "description": "Repository name",
          "required": true
        }
      },
      "tools": [
        "github:fetch-repo",
        "parser:dependencies",
        "reporter:generate"
      ]
    }
  },
  "tools": [
    {
      "name": "github:fetch-repo",
      "description": "從 GitHub API 獲取 repo 資訊"
    },
    {
      "name": "parser:dependencies",
      "description": "解析依賴文件"
    },
    {
      "name": "reporter:generate",
      "description": "生成 Markdown 報告"
    }
  ]
}

3.2 實現 Skill 邏輯

讓 Claude Code 輔助實現:

claude -p "
實現 tech-stack-analyzer skill:

需求:
1. 使用 GitHub API 獲取 repo 資訊
2. 支援分析的文件:
   - package.json (Node.js)
   - requirements.txt (Python)
   - go.mod (Go)
   - Cargo.toml (Rust)
   - pom.xml (Java)
3. 生成技術棧報告,包含:
   - 主要語言
   - 框架列表
   - 依賴數量
   - License 資訊

請:
- 使用 TypeScript
- 錯誤處理完善
- 添加型別定義
- 遵循 OpenClaw 約定
"

Claude Code 會生成

skills/tech-stack-analyzer/skill.ts

import { Skill, Tool, Context } from '@openclaw/sdk';

interface TechStack {
  languages: string[];
  frameworks: string[];
  dependencies: {
    total: number;
    direct: number;
    dev: number;
  };
  license: string;
}

export const techStackAnalyzer: Skill = {
  name: 'tech-stack-analyzer',
  description: '分析 GitHub repo 技術棧',

  async analyzeRepo(
    context: Context,
    params: { owner: string; repo: string }
  ): Promise<TechStack> {
    const { owner, repo } = params;

    // 1. Fetch repo info from GitHub
    const repoInfo = await context.tools['github:fetch-repo']({
      owner,
      repo
    });

    // 2. Detect language
    const languages = detectLanguages(repoInfo);

    // 3. Analyze dependencies
    const dependencies = await analyzeDependencies(
      context,
      repoInfo.defaultBranch
    );

    // 4. Extract license
    const license = repoInfo.license?.key || 'Unknown';

    return {
      languages,
      frameworks: extractFrameworks(dependencies),
      dependencies,
      license
    };
  }
};

3.3 實現工具(Tools)

claude -p "
為 tech-stack-analyzer 實現工具:

1. github-fetch-repo tool:
   - 使用 GitHub REST API
   - 支援認證(使用 GITHUB_TOKEN)
   - 獲取 repo 資訊、語言統計
   - 緩存機制(避免重複請求)

2. parser-dependencies tool:
   - 自動檢測包管理器
   - 解析依賴文件
   - 返回結構化數據

3. reporter-generate tool:
   - 生成 Markdown 報告
   - 包含視覺化圖表(使用 Mermaid)
   - 支援多語言輸出

請生成完整實作,包含:
- 型別定義
- 錯誤處理
- 日誌記錄
- 單元測試
"

第四步:測試 Skill

4.1 使用 Claude Code 生成測試

claude -p "
為 tech-stack-analyzer skill 生成測試:

測試場景:
1. 成功分析 Node.js repo
2. 成功分析 Python repo
3. 處理私有 repo(需要認證)
4. 處理不存在的 repo
5. 處理沒有依賴文件的 repo

請使用:
- Vitest(OpenClaw 的測試框架)
- Mock 外部 API
- 覆蓋邊界情況
"

生成的測試文件 skill.test.ts

import { describe, it, expect, vi } from 'vitest';
import { techStackAnalyzer } from './skill';

describe('tech-stack-analyzer', () => {
  it('should analyze Node.js repo', async () => {
    const mockContext = {
      tools: {
        'github:fetch-repo': vi.fn().mockResolvedValue({
          language: 'TypeScript',
          languages: { TypeScript: 80, JavaScript: 20 },
          license: { key: 'MIT' },
          defaultBranch: 'main'
        })
      }
    };

    const result = await techStackAnalyzer.analyzeRepo(
      mockContext as any,
      { owner: 'facebook', repo: 'react' }
    );

    expect(result.languages).toContain('TypeScript');
    expect(result.license).toBe('MIT');
  });

  // ... 更多測試
});

4.2 執行測試

# 在 skill 目錄
pnpm test

# 或使用 watch 模式
pnpm test:watch

# 查看覆蓋率
pnpm test:coverage

4.3 使用 Claude Code 除錯

# 如果測試失敗
claude -p "
除錯這個測試失敗:

[貼上測試錯誤訊息]

請:
1. 分析錯誤原因
2. 提供修復建議
3. 生成修復後的代碼
"

第五步:本地測試 Skill

5.1 啟動 OpenClaw 開發環境

# 在 OpenClaw 根目錄
pnpm dev

# 這會啟動:
# - Core services
# - Web UI (http://localhost:3000)
# - WebSocket connections
# - Hot reload

5.2 測試 Skill

# 使用 OpenClaw CLI 測試
npx openclaw skill test tech-stack-analyzer \
  --owner facebook \
  --repo react

# 或使用 Web UI
# http://localhost:3000/skills/tech-stack-analyzer

5.3 查看日誌

# 使用 Claude Code 分析日誌
claude -p "
分析這些 OpenClaw 日誌:

[貼上日誌]

請找出:
1. 是否有錯誤
2. 性能瓶頸
3. 改進建議
"

第六步:優化與完善

6.1 添加型別安全

claude -p "
為 tech-stack-analyzer 添加完整型別定義:

請使用:
- TypeScript 嚴格模式
- Interface 定義所有輸入輸出
- Generic types 支援多種 repo 類型
- Zod 運行時驗證
"

6.2 添加文檔

claude -p "
生成 skill 文檔:

包含:
1. README.md(使用說明)
2. API.md(API 文檔)
3. EXAMPLES.md(使用範例)
4. CONTRIBUTING.md(貢獻指南)

請遵循 OpenClaw 文檔標準
"

6.3 性能優化

claude -p "
優化 tech-stack-analyzer 性能:

當前問題:
- GitHub API 請求慢
- 沒有緩存機制
- 大型 repo 分析耗時長

請實現:
1. 智能緩存(Redis)
2. 並行請求
3. 增量更新
4. 批次處理
"

第七步:部署到生產環境

7.1 Docker 部署

# 構建 Docker image
docker build -t openclaw-tech-stack-analyzer .

# 測試運行
docker run -d \
  -p 3000:3000 \
  -env GITHUB_TOKEN=$GITHUB_TOKEN \
  openclaw-tech-stack-analyzer

7.2 雲端部署(Render)

# 使用 Claude Code 生成 Render 配置
claude -p "
生成 Render.com 部署配置:

需求:
- 自動從 GitHub 部署
- 環境變量配置
- 健康檢查
- 日誌收集
"

7.3 發布到 OpenClaw Skills Registry

# 1. 更新版本
npm version patch

# 2. 發布
npm publish

# 3. 提交到 registry
# https://skills.openclaw.dev/submit

第八步:持續維護

8.1 設置 CI/CD

claude -p "
為 tech-stack-analyzer 設置 GitHub Actions:

需求:
1. 自動測試(push/PR)
2. 代碼品質檢查(ESLint, Prettier)
3. 自動發布(tag 觸發)
4. 依賴更新(Dependabot)
"

8.2 監控與日誌

claude -p "
實現監控系統:

需求:
1. 使用情況統計
2. 錯説追蹤(Sentry)
3. 性能監控
4. 用戶反饋收集
"

最佳實踐

1. 開發流程

graph LR
    A[需求分析] --> B[Claude Code 設計]
    B --> C[實作核心功能]
    C --> D[編寫測試]
    D --> E{測試通過?}
    E -->|No| F[Claude Code 除錯]
    F --> C
    E -->|Yes| G[代碼審查]
    G --> H[部署]
    H --> I[監控]

2. 錯誤處理

// ✅ 好的錯誤處理
async function analyzeRepo(owner: string, repo: string) {
  try {
    const info = await fetchRepoInfo(owner, repo);
    return processInfo(info);
  } catch (error) {
    if (error instanceof NotFoundError) {
      throw new SkillError(
        `Repository ${owner}/${repo} not found`,
        'NOT_FOUND'
      );
    }
    if (error instanceof AuthError) {
      throw new SkillError(
        'GitHub authentication failed',
        'AUTH_ERROR'
      );
    }
    throw new SkillError(
      'Failed to analyze repository',
      'UNKNOWN_ERROR',
      { originalError: error }
    );
  }
}

// ❌ 不好的錯誤處理
async function analyzeRepo(owner: string, repo: string) {
  const info = await fetchRepoInfo(owner, repo); // 可能拋出未處理錯誤
  return processInfo(info);
}

3. 日誌記錄

// ✅ 結構化日誌
context.logger.info('Analyzing repository', {
  owner,
  repo,
  timestamp: new Date().toISOString()
});

// ❌ 非結構化日誌
console.log(`Analyzing ${owner}/${repo}`);

4. 測試覆蓋率

# 目標:80%+ 覆蓋率
pnpm test:coverage

# 查看未覆蓋的代碼
open coverage/index.html

常見問題

Q1: Skill 無法載入?

檢查清單

# 1. 檢查 manifest.json 語法
cat manifest.json | jq .

# 2. 檢查 TypeScript 編譯
pnpm build

# 3. 查看日誌
tail -f logs/openclaw.log

Q2: GitHub API 速率限制?

解決方案

// 使用認證提升限制
const token = process.env.GITHUB_TOKEN;
const headers = {
  'Authorization': `token ${token}`,
  'Accept': 'application/vnd.github.v3+json'
};

// 實施指數退避
async function fetchWithRetry(url: string, retries = 3) {
  for (let i = 0; i < retries; i++) {
    try {
      return await fetch(url, { headers });
    } catch (error) {
      if (i === retries - 1) throw error;
      await sleep(Math.pow(2, i) * 1000);
    }
  }
}

Q3: 如何與其他 Skills 整合?

// 在 skill 中調用其他 skills
const result = await context.skills['another-skill'].execute({
  param1: 'value1'
});

範例 Skills

1. GitHub Auto-Labeler

# 自動為 PR 分配標籤
skills/github-auto-labeler
├── skill.ts
├── manifest.json
└── tests/

2. Notion Meeting Notes

# 自動生成會議紀錄並同步到 Notion
skills/notion-meeting-notes
├── skill.ts
├── manifest.json
└── tests/

3. Daily Standup Bot

# 每日站會機器人
skills/daily-standup-bot
├── skill.ts
├── manifest.json
└── tests/

進階主題

1. 使用 MCP Servers

// 整合 Claude Code MCP servers
import { mcp } from '@openclaw/sdk';

const memory = await mcp.call('memory', {
  action: 'store',
  key: 'repo-analysis',
  value: analysis
});

2. 實現 Stream 處理

// 支援即時回饋
async function* analyzeStream(repo: string) {
  yield { type: 'progress', message: 'Fetching repo...' };
  const info = await fetchRepo(repo);

  yield { type: 'progress', message: 'Analyzing...' };
  const stack = await analyzeStack(info);

  yield { type: 'result', data: stack };
}

3. 多模型支援

// 根據任務選擇模型
const model = selectModel({
  complexity: 'high',
  cost: 'medium',
  speed: 'fast'
});

const result = await model.complete(prompt);

資源與社群

官方資源

開發工具

學習資源


總結

開發流程回顧

1. 準備環境 → 安裝工具
2. 創建 Skill → Claude Code 輔助
3. 實現功能 → TDD 開發
4. 測試除錯 → Vitest + Claude Code
5. 優化完善 → 型別、文檔、性能
6. 部署發布 → Docker / Cloud
7. 持續維護 → CI/CD + 監控

關鍵收穫

高效開發:Claude Code 加速 3-5 倍 ✅ 品質保證:TDD + 自動測試 ✅ 最佳實踐:遵循 OpenClaw 標準 ✅ 持續改進:監控與反饋循環

下一步

  1. 創建你的第一個 Skill

    claude -p "創建 OpenClaw skill:[你的想法]"
  2. 分享到社群

    • 發布到 GitHub
    • 提交到 Skills Registry
    • 在 Discord 分享
  3. 持續學習

    • 閱讀其他 Skills 源碼
    • 參與社群討論
    • 貢獻回專案

快開始構建你的第一個 OpenClaw Skill 吧!


原文:Building OpenClaw Skills with Claude Code