Chuyển đến nội dung chính

レッスン 4: インライン チャットとスマート アクション — コードをその場で編集する

対象を絞った編集、リファクタリング、バグ修正のためのインライン チャット (Cmd+I)。スマート アクション: コミット メッセージの生成、シンボルの名前変更、エラーの修正、セマンティック検索。コパイロットによるクイックフィックス。日常のワークフローに統合します。

💻 プログラミング — レッスン 4 レッスン 4: インライン チャットとスマート アクション — 編集 コードをその場で編集する

GitHub Copilot を使用した Vibe コーディング: 基本から高度まで

パート 1: Vibe コーディング プラットフォームと GitHub Copilot

xdev.asia

1. インラインチャット — その場でコードを編集

インラインチャット 小さなプロンプトを開くことができます エディタ内ですぐに、必要な変更を説明すると、Copilot はチャット ビューに切り替えることなく、その場でコードを編集します。

インラインチャットを開く

  • macOS: Cmd+I
  • Windows/Linux: Ctrl+I

基本的なワークフロー:

  1. 編集したいコードを選択(選択)します(またはコードを追加したい場所にカーソルを置きます)。
  2. プレス Cmd+I
  3. 変更の説明を英語/ベトナム語で入力します
  4. インラインの差分表示を確認する
  5. プレス 受け入れる または 廃棄する

2. インライン チャットの一般的な使用例

2.1.エラー処理を追加する

// Select function này → Cmd+I → "Add try-catch error handling with proper logging"

async function fetchUserData(userId: string) { const response = await fetch(/api/users/${userId}); const data = await response.json(); return data; }

// Copilot sẽ suggest: async function fetchUserData(userId: string) { try { const response = await fetch(/api/users/${userId}); if (!response.ok) { throw new Error(HTTP error! status: ${response.status}); } const data = await response.json(); return data; } catch (error) { console.error(Failed to fetch user ${userId}:, error); throw error; } }

2.2.コードのリファクタリング

# Select block code → Cmd+I → "Refactor to use list comprehension"

Trước:

result = [] for item in items: if item.price > 100: result.append(item.name)

Sau (Copilot suggest):

result = [item.name for item in items if item.price > 100]

2.3. TypeScript タイプを追加する

// Select → Cmd+I → "Add TypeScript type annotations"

// Trước: function processOrder(order, discount) { const total = order.items.reduce((sum, item) => sum + item.price, 0); return total * (1 - discount); }

// Sau: interface OrderItem { id: string; name: string; price: number; }

interface Order { id: string; items: OrderItem[]; }

function processOrder(order: Order, discount: number): number { const total = order.items.reduce((sum, item) => sum + item.price, 0); return total * (1 - discount); }

2.4.ドキュメントの生成

# Select function → Cmd+I → "Add docstring with parameters and return type"
def calculate_compound_interest(principal, rate, time, n=12):
    """
    Calculate compound interest.
Args:
    principal (float): Initial investment amount.
    rate (float): Annual interest rate (as a decimal, e.g., 0.05 for 5%).
    time (float): Time period in years.
    n (int): Number of times interest is compounded per year. Defaults to 12.

Returns:
    float: The total amount after compound interest.
"""
return principal * (1 + rate / n) ** (n * time)

2.5.単体テストを書く

// Select function → Cmd+I → "Generate unit tests using Jest"
// Copilot tự sinh test cases bao gồm happy path, edge cases, error cases

3. スマート アクション — AI をワークフローに統合

スマートアクションはAIのアクションです 組み込まれています VS Code インターフェイスに入ると、チャットを開かなくても、必要な場所にすぐに表示されます。

3.1.コミットメッセージの生成

  1. オープンソース管理ビュー (Ctrl+Shift+G)
  2. 変化をステージングする
  3. クリック キラキラアイコン✨ コミットメッセージ入力の横にあります
  4. Copilot は変更を分析し、従来のコミットに従ってコミット メッセージを生成します
// Ví dụ generated commit message:
feat(auth): add JWT token refresh mechanism

- Add refreshToken endpoint to AuthController
- Implement token rotation with configurable expiry
- Add middleware to auto-refresh expired tokens

3.2.コパイロットで修正する (クイック修正)

VS Code でエラー (赤い波線) が表示される場合:

  1. エラーにカーソルを合わせる → クリック 「クイックフィックス」
  2. 選択 「副操縦士で修正してください」
  3. Copilot はエラー メッセージを読み取り、コンテキストを分析し、修正を提案します

3.3.副操縦士で説明する

複雑なコードを選択→右クリック→ 「副操縦士」→「説明してください」

Copilot は自然言語でコードを説明するため、他の人のコードや AI が生成したコードを読むときに役立ちます。

3.4.テストの生成

関数を右クリック→ 「コパイロット」→「テストの生成」

Copilot は、プロジェクトのフレームワーク (Jest、Pytest、Go テストなど) に一致するテスト ケースを含むテスト ファイルを自動的に作成します。

3.5.テストの失敗を修正する

テスト エクスプローラーでテストが失敗した場合:

  1. 失敗したテストをクリックします
  2. 選択 「副操縦士で修正してください」
  3. Copilot はテスト失敗メッセージを読み取り、根本原因を見つけて、コードの修正 (テスト修正ではありません) を提案します。

副操縦士が提供される セマンティック検索 — テキストの一致だけでなく、意味によって検索します。

// Traditional search: tìm "authenticate"
// Kết quả: chỉ những chỗ có chính xác từ "authenticate"

// Semantic search: tìm "user login process"
// Kết quả: authenticate(), verifyCredentials(), signIn(), checkPassword()
// → Tìm được code liên quan dù không match exact text

5. インライン チャット、エージェント、チャットをいつ使用するか?

特長 いつ使用するか 範囲
インライン提案 コードフローは中断されません 現在の行/ブロック
インラインチャット 具体的に編集、リファクタリング、ドキュメントを追加する 選択したコードまたはカーソル位置
チャットビュー(質問) Q&A、説明、ブレインストーミング コードを変更しないでください
エージェントモード ビルド機能、複数ファイルの変更 プロジェクト全体
Scope nhỏ → lớn:
Inline Suggestions → Inline Chat → Chat (Ask) → Agent Mode
     (line)          (selection)      (Q&A)       (project)

6. 効果的なインライン チャットのためのヒント

  • 正しく選択してください: 冗長でも欠落でもない、編集する正しいコード部分を選択してください
  • 明確な説明: 「メールと電話の入力検証を追加する」は「これを検証する」よりも優れています
  • 一度に 1 つの変更: 大きな変更を多数の小さなインライン チャットに分割します。
  • コード用語を使用する: 「これを分離する」のではなく「ヘルパー関数に抽出する」
  • 承諾する前に確認してください: diff、特に変更ロジックを注意深く読んでください。

7. 練習問題

ファイルの作成 スマートアクションプラクティス.ts:

// Bài tập 1: Select function → Cmd+I → "Add error handling"
function divideNumbers(a, b) {
  return a / b;
}

// Bài tập 2: Select → Cmd+I → "Convert to arrow function with types"
function greetUser(name) {
  return "Hello, " + name + "!";
}

// Bài tập 3: Select → Cmd+I → "Add JSDoc documentation"
function calculateDiscount(price, percentage, maxDiscount) {
  const discount = price * percentage / 100;
  return Math.min(discount, maxDiscount);
}

// Bài tập 4: Tạo git commit → dùng ✨ để generate commit message
// Bài tập 5: Tạo lỗi cố ý → dùng "Fix with Copilot" để sửa

8. まとめ

インライン チャットとスマート アクションはツールです 精密な編集 — 次のことが可能になります。

  • ✅ コードを迅速にリファクタリングする
  • ✅ 1 つのプロンプトでエラー処理、タイプ、ドキュメントを追加
  • ✅ フルコンテキストでバグを修正
  • ✅ コミットメッセージをインテリジェントに生成
  • ✅ コンテキストを切り替えることなくコーディングフローを維持

次のセクションでは (パート 2)、Copilot の最も強力な機能について説明します — エージェントモード、AI が自動的にコードを記述し、ファイルを作成し、コマンドを実行して、完全な機能を構築します。