GitHub Copilot เทคนิคการใช้งานให้เต็มประสิทธิภาพ
GitHub Copilot เป็นหนึ่งใน AI Coding Assistants ที่ได้รับความนิยมมากที่สุด ในปี 2025 แต่หลายคนยังใช้งานได้ไม่เต็มศักยภาพ บทความนี้จะรวมเทคนิคและ tricks ที่จะช่วยให้คุณใช้ Copilot ได้อย่างมืออาชีพ
เริ่มต้นกับ GitHub Copilot
การติดตั้ง
- ติดตั้ง extension "GitHub Copilot" ใน VS Code
- Sign in ด้วย GitHub account
- Activate subscription (หรือใช้ free trial)
Plans และราคา
| Plan | ราคา | เหมาะกับ |
|---|---|---|
| Individual | $10/เดือน | นักพัฒนาทั่วไป |
| Business | $19/เดือน/user | ทีมขนาดเล็ก-กลาง |
| Enterprise | $39/เดือน/user | องค์กรขนาดใหญ่ |
| Free | $0 | Students, OSS maintainers |
Keyboard Shortcuts ที่ต้องรู้
Essential Shortcuts
| Shortcut (Mac) | Shortcut (Windows) | Action |
|---|---|---|
Tab | Tab | Accept suggestion |
Esc | Esc | Dismiss suggestion |
Alt+] | Alt+] | Next suggestion |
Alt+[ | Alt+[ | Previous suggestion |
Cmd+Enter | Ctrl+Enter | Open Copilot panel |
Copilot Chat Shortcuts
| Shortcut | Action |
|---|---|
Cmd+I | Inline Chat |
Cmd+Shift+I | Open Chat panel |
/explain | Explain selected code |
/fix | Fix bugs in selection |
/tests | Generate tests |
/doc | Generate documentation |
เทคนิคพื้นฐาน
1. ใช้ Comments เป็น Prompts
Copilot เข้าใจ comments ได้ดีมาก ใช้เป็น prompt ได้เลย:
// Function to validate Thai phone number (starts with 0, 10 digits)
function validateThaiPhone(phone) {
// Copilot จะ suggest:
const phoneRegex = /^0[0-9]{9}$/;
return phoneRegex.test(phone);
}
2. ให้ Context ที่ดี
// ❌ ไม่ดี - ไม่มี context
function calc(a, b) {
// ✅ ดี - มี context ชัดเจน
/**
* Calculate compound interest
* @param principal - Initial amount
* @param rate - Annual interest rate (decimal)
* @param time - Time in years
* @param n - Number of times compounded per year
* @returns Final amount after compound interest
*/
function calculateCompoundInterest(principal, rate, time, n) {
// Copilot จะ generate โค้ดที่ถูกต้อง
return principal * Math.pow((1 + rate / n), n * time);
}
3. พิมพ์ Function Signature ก่อน
// พิมพ์ signature แล้วรอ Copilot
async function fetchUserProfile(userId: string): Promise<UserProfile> {
// Copilot จะ suggest implementation
}
interface PaginationParams {
page: number;
limit: number;
sortBy?: string;
order?: 'asc' | 'desc';
}
// Copilot เห็น interface แล้วจะ suggest ได้ดีขึ้น
async function fetchUsers(params: PaginationParams): Promise<User[]> {
// ...
}
เทคนิคขั้นกลาง
4. ใช้ Copilot Chat Commands
/explain - อธิบายโค้ด
Select โค้ดที่ต้องการ → Cmd+I → พิมพ์ /explain
"อธิบายว่า regular expression นี้ทำอะไร"
/fix - แก้ bugs
Select โค้ดที่มี bug → /fix
Copilot จะวิเคราะห์และเสนอวิธีแก้ไข
/tests - สร้าง unit tests
// Select function นี้
function calculateDiscount(price, discountPercent) {
if (discountPercent < 0 || discountPercent > 100) {
throw new Error('Invalid discount percentage');
}
return price * (1 - discountPercent / 100);
}
// /tests จะ generate:
describe('calculateDiscount', () => {
it('should calculate 20% discount correctly', () => {
expect(calculateDiscount(100, 20)).toBe(80);
});
it('should return original price for 0% discount', () => {
expect(calculateDiscount(100, 0)).toBe(100);
});
it('should throw error for negative discount', () => {
expect(() => calculateDiscount(100, -10)).toThrow('Invalid discount percentage');
});
it('should throw error for discount over 100%', () => {
expect(() => calculateDiscount(100, 150)).toThrow('Invalid discount percentage');
});
});
/doc - สร้าง documentation
// Select function → /doc
function mergeArrays(arr1, arr2, removeDuplicates = true) {
const merged = [...arr1, ...arr2];
return removeDuplicates ? [...new Set(merged)] : merged;
}
// Copilot จะ generate:
/**
* Merges two arrays into one.
*
* @param {Array} arr1 - The first array to merge.
* @param {Array} arr2 - The second array to merge.
* @param {boolean} [removeDuplicates=true] - Whether to remove duplicate values.
* @returns {Array} The merged array.
*
* @example
* mergeArrays([1, 2], [2, 3]); // returns [1, 2, 3]
* mergeArrays([1, 2], [2, 3], false); // returns [1, 2, 2, 3]
*/
5. ใช้ Inline Chat (Cmd+I)
Inline Chat ช่วยให้แก้ไขโค้ดได้เร็วกว่า:
// Select โค้ดนี้
const data = response.data;
const users = data.users;
const total = data.total;
// Cmd+I → "Convert to destructuring"
// Result:
const { users, total } = response.data;
6. Multi-file Awareness
Copilot เข้าใจ context จากไฟล์อื่นใน project:
// types.ts (ไฟล์แยก)
export interface Product {
id: string;
name: string;
price: number;
category: string;
inStock: boolean;
}
// products.ts (Copilot จะเห็น types.ts)
import { Product } from './types';
// พิมพ์แค่นี้
function filterProducts(products: Product[], category: string): Product[] {
// Copilot จะ suggest โดยรู้จัก Product interface
return products.filter(p => p.category === category && p.inStock);
}
เทคนิคขั้นสูง
7. Pattern-based Suggestions
Copilot เรียนรู้จาก patterns ที่คุณใช้:
// เขียน handler แรก
const handleNameChange = (e) => {
setName(e.target.value);
};
// พอพิมพ์ handler ที่สอง Copilot จะ suggest ตาม pattern
const handleEmailChange = (e) => {
setEmail(e.target.value);
};
const handlePasswordChange = (e) => {
setPassword(e.target.value);
};
8. Test-Driven Development with Copilot
เขียน test ก่อน แล้วให้ Copilot implement:
// เขียน tests ก่อน
describe('ShoppingCart', () => {
it('should add item to cart', () => {
const cart = new ShoppingCart();
cart.addItem({ id: '1', name: 'Shirt', price: 500, quantity: 1 });
expect(cart.items.length).toBe(1);
});
it('should calculate total correctly', () => {
const cart = new ShoppingCart();
cart.addItem({ id: '1', name: 'Shirt', price: 500, quantity: 2 });
cart.addItem({ id: '2', name: 'Pants', price: 800, quantity: 1 });
expect(cart.getTotal()).toBe(1800);
});
it('should apply discount', () => {
const cart = new ShoppingCart();
cart.addItem({ id: '1', name: 'Shirt', price: 1000, quantity: 1 });
cart.applyDiscount(10); // 10%
expect(cart.getTotal()).toBe(900);
});
});
// จากนั้นให้ Copilot implement class
class ShoppingCart {
// Copilot จะ suggest implementation ตาม tests
}
9. API Integration Patterns
// สร้าง pattern สำหรับ API calls
// Copilot จะเรียนรู้และ suggest ตาม pattern
// Pattern 1: Basic fetch wrapper
async function apiGet(endpoint) {
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
headers: {
'Authorization': `Bearer ${getToken()}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new ApiError(response.status, await response.text());
}
return response.json();
}
// ตอนพิมพ์ apiPost, apiPut, apiDelete
// Copilot จะ suggest ตาม pattern apiGet
async function apiPost(endpoint, data) {
// Copilot suggests...
}
10. React Component Patterns
// เขียน component แรกอย่างละเอียด
interface ButtonProps {
variant: 'primary' | 'secondary' | 'danger';
size: 'sm' | 'md' | 'lg';
children: React.ReactNode;
onClick?: () => void;
disabled?: boolean;
}
export function Button({ variant, size, children, onClick, disabled }: ButtonProps) {
const baseClasses = 'rounded font-medium transition-colors';
const variantClasses = {
primary: 'bg-blue-500 text-white hover:bg-blue-600',
secondary: 'bg-gray-200 text-gray-800 hover:bg-gray-300',
danger: 'bg-red-500 text-white hover:bg-red-600'
};
const sizeClasses = {
sm: 'px-2 py-1 text-sm',
md: 'px-4 py-2 text-base',
lg: 'px-6 py-3 text-lg'
};
return (
<button
className={`${baseClasses} ${variantClasses[variant]} ${sizeClasses[size]}`}
onClick={onClick}
disabled={disabled}
>
{children}
</button>
);
}
// ตอนสร้าง Input, Select, Card components
// Copilot จะ suggest ตาม pattern Button
Copilot Chat Advanced Usage
Context-aware Conversations
User: @workspace How is authentication implemented in this project?
Copilot: Based on the codebase, authentication is implemented using:
1. JWT tokens stored in cookies
2. Supabase Auth for user management
3. Middleware for route protection
...
User: Can you show me how to add a new protected route?
Copilot: [Shows code based on existing patterns in the project]
Workspace Scoping
ใช้ @workspace เพื่อถามเกี่ยวกับทั้ง project:
@workspace Where is the database connection configured?
@workspace List all API endpoints
@workspace How do I add a new database migration?
File Reference
ใช้ #file เพื่อ reference ไฟล์เฉพาะ:
#file:src/utils/auth.ts Can you explain the refreshToken function?
#file:package.json What testing framework does this project use?
Best Practices
1. ตรวจสอบโค้ดเสมอ
// ❌ Accept โดยไม่ดู
// Tab ทันทีที่เห็น suggestion
// ✅ Review ก่อน accept
// - อ่านโค้ดที่ suggest
// - ตรวจสอบ logic
// - ดู edge cases
// - Check security implications
2. ใช้ความเฉพาะเจาะจง
// ❌ Comment ทั่วไป
// get users
// ✅ Comment เฉพาะเจาะจง
// Fetch paginated list of active users with their roles
// Returns: { users: User[], total: number, hasMore: boolean }
async function getActiveUsersWithRoles(page = 1, limit = 20) {
3. สร้าง Code Standards
// สร้างไฟล์ตัวอย่างที่ดี
// Copilot จะเรียนรู้จาก patterns เหล่านี้
// example-service.ts
export class ExampleService {
constructor(private db: Database) {}
async findById(id: string): Promise<Example | null> {
try {
const result = await this.db.query('SELECT * FROM examples WHERE id = $1', [id]);
return result.rows[0] || null;
} catch (error) {
logger.error('ExampleService.findById failed', { id, error });
throw new DatabaseError('Failed to find example');
}
}
}
4. Iterate อย่างต่อเนื่อง
// Round 1: Basic implementation
function processData(data) {
return data.map(item => item.value);
}
// Round 2: Add type safety (Cmd+I: "Add TypeScript types")
function processData(data: DataItem[]): number[] {
return data.map(item => item.value);
}
// Round 3: Add error handling (Cmd+I: "Add null checks and error handling")
function processData(data: DataItem[] | null): number[] {
if (!data || data.length === 0) {
return [];
}
return data.map(item => item.value ?? 0);
}
Common Issues และวิธีแก้
Suggestions ไม่ตรงใจ
วิธีแก้:
1. เพิ่ม context ใน comments
2. เขียน function signature ให้ชัดเจน
3. ใช้ Alt+] เพื่อดู suggestions อื่น
4. กด Esc แล้วเขียน comment ใหม่
Copilot ช้า
วิธีแก้:
1. ตรวจสอบ internet connection
2. ลอง disable/enable extension
3. Clear VS Code cache
4. ตรวจสอบว่า subscription active
โค้ดซ้ำกับ Open Source
วิธีแก้:
1. เปิด "Copilot: Configure Duplicate Detection"
2. ดู notification เมื่อ code อาจ match กับ public code
3. ตรวจสอบ license compatibility
สรุป
GitHub Copilot เป็นเครื่องมือที่ทรงพลังสำหรับ Vibe Coding แต่ต้องใช้ให้ถูกวิธี:
Key Takeaways
- ใช้ comments เป็น prompts - ยิ่งละเอียดยิ่งดี
- เขียน function signatures ก่อน - ช่วยให้ Copilot เข้าใจ
- ใช้ Chat commands - /explain, /fix, /tests, /doc
- Review เสมอ - ไม่ trust 100%
- สร้าง patterns - Copilot เรียนรู้จากโค้ดของคุณ
Next Steps
- ลอง Cursor IDE ถ้าต้องการ AI experience ที่ดีกว่า
- อ่าน Prompt Engineering เพื่อเขียน prompts ที่ดีขึ้น
- ศึกษา Best Practices สำหรับ Vibe Coding
พร้อมใช้ GitHub Copilot อย่างมืออาชีพแล้วหรือยัง?
เริ่มต้นด้วยการ activate subscription และทดลองเทคนิคเหล่านี้ใน project ของคุณ!
เขียนโดย
AI Unlocked Team
บทความอื่นๆ ที่น่าสนใจ
วิธีติดตั้ง FFmpeg บน Windows และ Mac: คู่มือฉบับสมบูรณ์
เรียนรู้วิธีติดตั้ง FFmpeg บน Windows และ macOS พร้อมการตั้งค่า PATH อย่างละเอียด เพื่อใช้งานโปรแกรมตัดต่อวิดีโอและเสียงระดับมืออาชีพ
สร้าง AI-Powered SaaS: จากไอเดียสู่ผลิตภัณฑ์
คู่มือครบวงจรในการสร้าง AI-Powered SaaS ตั้งแต่การวางแผน พัฒนา ไปจนถึง launch และ scale รวมถึง tech stack, pricing และ business model
AI Security: วิธีใช้ AI อย่างปลอดภัย
เรียนรู้แนวทางการใช้ AI อย่างปลอดภัย ครอบคลุม prompt injection, data privacy, API security และ best practices สำหรับองค์กร