Skip to content

Bí kíp VS Code 🚀

Editor của bạn là một công cụ. Hãy mài sắc nó.

Tip 1: User Snippets - Stop Typing Boilerplate

Problem

Bạn gõ cùng một đoạn code lặp đi lặp lại (React component, test template, API route).

Solution

Tạo custom snippets: gõ 4 chữ cái, nhận 20 dòng code.

Example

Tạo snippet cho React component:

  1. File > Preferences > Configure User Snippets
  2. Chọn typescriptreact.json
  3. Thêm:
json
{
  "React Functional Component": {
    "prefix": "rfc",
    "body": [
      "interface ${1:ComponentName}Props {",
      "  $2",
      "}",
      "",
      "export const ${1:ComponentName}: React.FC<${1:ComponentName}Props> = ({ $3 }) => {",
      "  return (",
      "    <div>",
      "      $0",
      "    </div>",
      "  );",
      "};"
    ],
    "description": "React Functional Component with TypeScript"
  }
}

Usage: Gõ rfc + Tab → Component template xuất hiện!

Pro Tips

  • $1, $2: Tab stops (nhấn Tab để nhảy qua)
  • $0: Final cursor position
  • ${1:ComponentName}: Placeholder với default value
  • Tạo snippets cho: API routes, test cases, database models

Tip 2: Essential Extensions (Professor Tom's Stack)

Problem

VS Code vanilla thiếu nhiều tính năng cần thiết cho professional development.

Solution

Install bộ extensions này (đã battle-tested qua 1000+ projects):

Example

Must-Have Extensions:

  1. GitLens - Git supercharged

    • Xem ai viết dòng code đó và khi nào
    • Blame inline, không cần mở Git history
    • Compare branches, view file history
  2. Error Lens - Inline error display

    • Lỗi hiển thị ngay cạnh code
    • Không cần hover vào squiggles đỏ
    • Warning và info cũng inline
  3. Prettier - Code formatter

    • Format on save
    • Không tranh cãi về style nữa
    • Config một lần, quên đi mãi mãi
  4. ESLint - Linter

    • Catch bugs trước khi chạy code
    • Enforce coding standards
    • Auto-fix nhiều issues
  5. Auto Rename Tag - HTML/JSX productivity

    • Đổi opening tag → closing tag tự động đổi
    • Tiết kiệm vô số lần sửa lỗi
  6. Path Intellisense - File path autocomplete

    • Autocomplete khi import files
    • Không gõ nhầm path nữa
  7. Better Comments - Highlight comments

    • // TODO: màu cam
    • // FIXME: màu đỏ
    • // NOTE: màu xanh
  8. Bracket Pair Colorizer 2 - (Built-in từ VS Code 1.60+)

    • Mỗi cặp ngoặc một màu
    • Dễ track nested logic
  9. Live Share - Pair programming

    • Code cùng nhau real-time
    • Share terminal, debug session
    • Remote collaboration
  10. REST Client - Test APIs trong VS Code

    • Không cần Postman
    • Save requests trong .http files
    • Version control API tests

Pro Tips

  • Disable extensions không dùng (chúng làm chậm VS Code)
  • Tạo workspace-specific extension recommendations
  • Sync extensions qua Settings Sync

Tip 3: Settings Sync - Never Configure Again

Problem

Mỗi lần setup máy mới, phải config lại VS Code từ đầu.

Solution

Settings Sync: Sync settings, extensions, keybindings qua GitHub/Microsoft account.

Example

  1. Ctrl + Shift + P → "Settings Sync: Turn On"
  2. Chọn GitHub hoặc Microsoft account
  3. Chọn gì cần sync (Settings, Extensions, Keybindings, Snippets)
  4. Done! Mọi thay đổi tự động sync

Pro Tips

  • Tạo profile riêng cho từng project type (Web, Python, Data Science)
  • Export settings thành JSON để backup
  • Share settings với team qua .vscode/settings.json

Tip 4: Workspace Settings - Project-Specific Config

Problem

Mỗi project có coding standards khác nhau (tab size, formatter, linter rules).

Solution

Tạo .vscode/settings.json trong project root.

Example

json
{
  "editor.tabSize": 2,
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "eslint.validate": ["javascript", "typescript", "vue"],
  "files.exclude": {
    "**/node_modules": true,
    "**/.git": true,
    "**/dist": true
  }
}

Pro Tips

  • Workspace settings override User settings
  • Commit .vscode/ vào Git để team dùng chung
  • Tạo .vscode/extensions.json để recommend extensions

Tip 5: Emmet - HTML/CSS Superpowers

Problem

Viết HTML/CSS tay quá chậm.

Solution

Emmet: Built-in trong VS Code, expand abbreviations thành code.

Example

html
<!-- Gõ: ul>li*5>a -->
<!-- Nhấn Tab → -->
<ul>
  <li><a href=""></a></li>
  <li><a href=""></a></li>
  <li><a href=""></a></li>
  <li><a href=""></a></li>
  <li><a href=""></a></li>
</ul>

<!-- Gõ: .container>.row>.col-md-6*2 -->
<!-- Nhấn Tab → -->
<div class="container">
  <div class="row">
    <div class="col-md-6"></div>
    <div class="col-md-6"></div>
  </div>
</div>

Pro Tips

  • Hoạt động trong JSX/Vue templates
  • CSS: m10margin: 10px;
  • Học syntax: Emmet Cheat Sheet

Tip 6: Tasks - Automate Workflows

Problem

Phải nhớ và gõ nhiều lệnh phức tạp (build, test, deploy).

Solution

Tạo .vscode/tasks.json để define custom tasks.

Example

json
{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Build Project",
      "type": "shell",
      "command": "npm run build",
      "group": {
        "kind": "build",
        "isDefault": true
      }
    },
    {
      "label": "Run Tests",
      "type": "shell",
      "command": "npm test",
      "group": "test"
    }
  ]
}

Usage: Ctrl + Shift + B → Chạy default build task

Pro Tips

  • Combine tasks: dependsOn: ["task1", "task2"]
  • Problem matchers: Parse output để show errors inline
  • Bind tasks to keybindings

Tip 7: Debugging Configuration - Stop console.log

Problem

Debug bằng console.log không hiệu quả, không professional.

Solution

Setup debugger trong VS Code với .vscode/launch.json.

Example

Node.js debugging:

json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug Server",
      "program": "${workspaceFolder}/src/server.ts",
      "preLaunchTask": "npm: build",
      "outFiles": ["${workspaceFolder}/dist/**/*.js"]
    }
  ]
}

Usage: F5 → Start debugging với breakpoints

Pro Tips

  • Set breakpoints: Click vào gutter bên trái line numbers
  • Conditional breakpoints: Right-click breakpoint → Edit Breakpoint
  • Logpoints: Breakpoint không dừng code, chỉ log
  • Debug tests: Tạo config riêng cho Jest/Mocha

Tip 8: Refactoring Tools - Code Smarter

Problem

Refactor code thủ công dễ sai và mất thời gian.

Solution

Dùng built-in refactoring tools của VS Code.

Example

Available Refactorings:

  • Extract Variable: Ctrl + Shift + R → Chọn "Extract to constant"
  • Extract Function: Chọn code block → Ctrl + Shift + R → "Extract to function"
  • Rename Symbol: F2 → Đổi tên variable/function ở mọi nơi
  • Move to new file: Right-click → "Move to new file"
typescript
// Before
const total = items.reduce((sum, item) => sum + item.price * item.quantity, 0);

// After Extract Function
const calculateTotal = (items: Item[]) => 
  items.reduce((sum, item) => sum + item.price * item.quantity, 0);

const total = calculateTotal(items);

Pro Tips

  • Refactoring tự động update imports
  • Undo refactoring: Ctrl + Z
  • Preview changes trước khi apply

Tip 9: Code Folding - Navigate Large Files

Problem

File quá dài, khó navigate và focus.

Solution

Fold/unfold code sections để collapse code không cần xem.

Example

typescript
// Fold function body
function processData() {  // ← Click arrow để fold
  // 50 lines of code...
}  // ← Collapsed thành 1 line

// Fold imports
import { ... } from '...';  // ← Fold tất cả imports

Shortcuts:

  • Ctrl + Shift + [: Fold region
  • Ctrl + Shift + ]: Unfold region
  • Ctrl + K, Ctrl + 0: Fold all
  • Ctrl + K, Ctrl + J: Unfold all

Pro Tips

  • Custom fold regions: // #region Name ... // #endregion
  • Fold by level: Ctrl + K, Ctrl + 1/2/3
  • Fold all comments: Ctrl + K, Ctrl + /

Tip 10: Integrated Source Control - Git Without Terminal

Problem

Chuyển qua terminal để dùng Git làm gián đoạn workflow.

Solution

Dùng integrated Source Control panel trong VS Code.

Example

Workflow:

  1. Ctrl + Shift + G: Mở Source Control panel
  2. Xem changes, stage files (click +)
  3. Gõ commit message
  4. Ctrl + Enter: Commit
  5. Click ... → Push

Advanced:

  • View diff: Click vào file trong Source Control
  • Stage hunks: Click + trên từng code block
  • Discard changes: Click -
  • View Git history: GitLens extension

Pro Tips

  • Commit message conventions: feat:, fix:, docs:
  • Amend last commit: ... → "Commit" → "Commit Staged (Amend)"
  • Resolve merge conflicts: VS Code highlights conflicts, click "Accept Current/Incoming"

📋 Quick Reference

FeatureShortcut/ActionBenefit
User SnippetsFile > Preferences > SnippetsStop typing boilerplate
Settings SyncCtrl + Shift + P → "Settings Sync"Never configure again
EmmetType abbreviation + TabHTML/CSS superpowers
Tasks.vscode/tasks.jsonAutomate workflows
DebuggingF5Stop console.log
RefactoringCtrl + Shift + RCode smarter
Code FoldingCtrl + Shift + [Navigate large files
Source ControlCtrl + Shift + GGit without terminal

🎯 Luyện tập ngay