GitHub Copilotとは
GitHub Copilotは、AIによるコード補完ツールです。コメントや関数名から意図を理解し、コードを自動生成します。
セットアップ
VS Code拡張機能
# VS Code拡張機能をインストール
# 1. Extensions (Ctrl+Shift+X) を開く
# 2. "GitHub Copilot" を検索
# 3. インストール
# 4. GitHubアカウントでサインイン
設定
// settings.json
{
"github.copilot.enable": {
"*": true,
"yaml": true,
"markdown": true,
"plaintext": false
},
"github.copilot.editor.enableAutoCompletions": true
}
基本的な使い方
コメントからコード生成
// ユーザーをIDで検索する関数
// Copilotが以下を提案
async function findUserById(id: string) {
const user = await db.users.findUnique({
where: { id },
});
return user;
}
// メールアドレスを検証する関数
function validateEmail(email: string): boolean {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
関数名から推測
// 関数名を入力すると実装を提案
function sortByDate(items: { date: Date }[]) {
return items.sort((a, b) => b.date.getTime() - a.date.getTime());
}
function calculateTax(price: number, rate: number = 0.1) {
return price * rate;
}
function formatCurrency(amount: number, currency: string = 'JPY') {
return new Intl.NumberFormat('ja-JP', {
style: 'currency',
currency,
}).format(amount);
}
テストコード生成
// sum.test.ts
// テストケースを入力すると、テストが生成される
describe('sum', () => {
it('should add two positive numbers', () => {
expect(sum(1, 2)).toBe(3);
});
it('should handle negative numbers', () => {
expect(sum(-1, 1)).toBe(0);
});
it('should handle zero', () => {
expect(sum(0, 0)).toBe(0);
});
});
プロンプトのコツ
具体的なコメントを書く
// ❌ 悪い例: 曖昧
// データを処理する
// ✅ 良い例: 具体的
// CSVファイルを読み込み、各行をオブジェクトに変換する
// ヘッダー行をキーとして使用
function parseCSV(csvContent: string) {
const lines = csvContent.trim().split('\n');
const headers = lines[0].split(',');
return lines.slice(1).map(line => {
const values = line.split(',');
return headers.reduce((obj, header, index) => {
obj[header.trim()] = values[index]?.trim();
return obj;
}, {} as Record<string, string>);
});
}
型情報を活用
// 型を定義すると、より正確な提案
interface User {
id: string;
name: string;
email: string;
createdAt: Date;
}
interface CreateUserInput {
name: string;
email: string;
}
// 型に基づいてCopilotが適切な実装を提案
async function createUser(input: CreateUserInput): Promise<User> {
const user: User = {
id: crypto.randomUUID(),
name: input.name,
email: input.email,
createdAt: new Date(),
};
await db.users.create({ data: user });
return user;
}
コンテキストを提供
// ファイルの先頭にコンテキストを書く
// このファイルは、Stripeの決済処理を行うサービスです
// Stripe Node.js SDKを使用します
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: '2023-10-16',
});
// 顧客を作成する
async function createCustomer(email: string, name: string) {
return stripe.customers.create({
email,
name,
});
}
// 支払いインテントを作成する
async function createPaymentIntent(amount: number, currency: string = 'jpy') {
return stripe.paymentIntents.create({
amount,
currency,
});
}
Copilot Chat
コード説明
# VS Code で Ctrl+I または Cmd+I でChatを開く
User: この関数を説明して
[選択したコードについて説明を得る]
User: このコードのバグを見つけて
[潜在的なバグや問題点を指摘]
User: この関数のユニットテストを書いて
[テストコードを生成]
リファクタリング
User: この関数をより読みやすくリファクタリングして
User: この処理を非同期処理に変換して
User: エラーハンドリングを追加して
ドキュメント生成
User: この関数のJSDocを書いて
/**
* ユーザーをIDで検索します
* @param id - ユーザーID
* @returns ユーザーオブジェクト、見つからない場合はnull
* @throws DatabaseError データベース接続エラー時
*/
キーボードショートカット
| 操作 | Windows/Linux | macOS |
|---|---|---|
| 提案を受け入れ | Tab | Tab |
| 提案を拒否 | Esc | Esc |
| 次の提案 | Alt+] | Option+] |
| 前の提案 | Alt+[ | Option+[ |
| Copilot Chat | Ctrl+I | Cmd+I |
| インライン提案を表示 | Ctrl+Enter | Cmd+Enter |
ベストプラクティス
1. 段階的に生成
// 一度に全てを生成せず、段階的に
// Step 1: インターフェース定義
interface Product {
id: string;
name: string;
price: number;
}
// Step 2: 関数シグネチャ
async function getProducts(): Promise<Product[]>
// Step 3: 実装
async function getProducts(): Promise<Product[]> {
const response = await fetch('/api/products');
return response.json();
}
2. 生成されたコードをレビュー
// Copilotの提案は必ずレビューする
// セキュリティ、パフォーマンス、ビジネスロジックを確認
// ⚠️ 生成されたSQLはインジェクション対策を確認
const query = `SELECT * FROM users WHERE id = ?`; // プリペアドステートメント使用
// ⚠️ APIキーなどがハードコードされていないか確認
const apiKey = process.env.API_KEY; // 環境変数を使用
3. プロジェクト固有のパターンを学習させる
// プロジェクトのパターンを先に書くと、
// 同じパターンで提案してくれる
// エラーハンドリングのパターン
class AppError extends Error {
constructor(
public code: string,
message: string,
public statusCode: number = 500
) {
super(message);
}
}
// この後、同様のパターンで提案される
制限事項
- 最新のAPIやライブラリは学習していない可能性
- プロプライエタリなコードは提案されない
- 大規模なコード生成は分割が必要
- セキュリティクリティカルなコードは要レビュー
関連記事
- VS Code設定 - エディタ設定
- TypeScript入門 - 型システム活用
- テスト自動化 - テスト作成
まとめ
GitHub Copilotは、具体的なコメントと型情報を提供することで、より正確なコードを生成します。生成されたコードは必ずレビューし、プロジェクトの品質基準を満たしているか確認しましょう。
← Back to list