Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

VS Code Extension Patterns

БесплатноБез исполняемых скриптовНе проверен

Expert knowledge of VS Code Extension API patterns, TreeDataProvider implementation, and command registration

drewipsonот drewipson★ 26 звёзд на GitHub14 установок в других каталогах

Об этом скилле

VS Code Extension Patterns Skill

This skill provides deep expertise in VS Code Extension API patterns, common implementations, and best practices for building robust VS Code extensions.

Core Competencies

1. TreeDataProvider Implementation

Expert knowledge of implementing tree views in VS Code extensions:

export class MyTreeProvider implements vscode.TreeDataProvider<TreeItem> {
  // Event emitter for refresh notifications
  private _onDidChangeTreeData = new vscode.EventEmitter<TreeItem | undefined>();
  readonly onDidChangeTreeData = this._onDidChangeTreeData.event;

  // Trigger refresh
  refresh(): void {
    this._onDidChangeTreeData.fire(undefined);
  }

  // Convert data to tree item
  getTreeItem(element: TreeItem): vscode.TreeItem {
    const item = new vscode.TreeItem(
      element.label,
      element.children ? vscode.TreeItemCollapsibleState.Collapsed : vscode.TreeItemCollapsibleState.None
    );

    // Set icon using ThemeIcon for consistency
    item.iconPath = new vscode.ThemeIcon('file');

    // Add command for click action
    item.command = {
      command: 'extension.openItem',
      title: 'Open',
      arguments: [element]
    };

    // Set context value for context menu filtering
    item.contextValue = element.type;

    return item;
  }

  // Get children for a node
  async getChildren(element?: TreeItem): Promise<TreeItem[]> {
    if (!element) {
      return this.getRootItems();
    }
    return element.children || [];
  }
}

Key Patterns:

  • Use EventEmitter for change notifications
  • Implement getTreeItem() and getChildren() methods
  • Set contextValue for context menu filtering
  • Use ThemeIcon for built-in icons
  • Attach commands to tree items for click actions
  • Handle async data loading in getChildren()

2. Command Registration

Proper command registration patterns:

export function activate(context: vscode.ExtensionContext) {
  // Register command
  const disposable = vscode.commands.registerCommand(
    'extension.myCommand',
    async (...args) => {
      try {
        // Command implementation
        vscode.window.showInformationMessage('Command executed!');
      } catch (error) {
        vscode.window.showErrorMessage(
          `Command failed: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    }
  );

  // CRITICAL: Add to subscriptions for disposal
  context.subscriptions.push(disposable);
}

Best Practices:

  • Always add disposables to context.subscriptions
  • Handle errors and show user-friendly messages
  • Use async/await for asynchronous operations
  • Validate arguments before processing
  • Provide meaningful error messages

3. Extension Lifecycle

Understanding extension activation and deactivation:

// Activation
export async function activate(context: vscode.ExtensionContext) {
  console.log('Extension activating...');

  // Register providers
  const treeProvider = new MyTreeProvider();
  vscode.window.registerTreeDataProvider('myView', treeProvider);

  // Register commands
  context.subscriptions.push(
    vscode.commands.registerCommand('extension.refresh', () => {
      treeProvider.refresh();
    })
  );

  // Set up file watchers
  const watcher = vscode.workspace.createFileSystemWatcher('**/*.config');
  watcher.onDidChange(() => treeProvider.refresh());
  context.subscriptions.push(watcher);

  console.log('Extension activated successfully');
}

// Deactivation (cleanup)
export function deactivate() {
  console.log('Extension deactivating...');
  // Cleanup if needed (disposables auto-disposed)
}

Activation Events:

  • onStartupFinished - Activate after VS Code loads (recommended)
  • * - Activate immediately (use sparingly)
  • onCommand: - Activate when command executed
  • onView: - Activate when view opened
  • onLanguage: - Activate for specific file types

4. Configuration Management

Working with VS Code settings:

// Read configuration
const config = vscode.workspace.getConfiguration('myExtension');
const setting = config.get<string>('mySetting', 'defaultValue');

// Write configuration
await config.update('mySetting', newValue, vscode.ConfigurationTarget.Global);

// Listen for configuration changes
context.subscriptions.push(
  vscode.workspace.onDidChangeConfiguration(e => {
    if (e.affectsConfiguration('myExtension.mySetting')) {
      // Reload or update based on new setting
      treeProvider.refresh();
    }
  })
);

Configuration Targets:

  • Global - User settings
  • Workspace - Workspace settings
  • WorkspaceFolder - Folder-specific settings

5. File System Watchers

Monitoring file changes:

// Watch specific pattern
const watcher = vscode.workspace.createFileSystemWatcher(
  new vscode.RelativePattern(workspaceFolder, '.claude/**/*')
);

// Handle events
watcher.onDidCreate(uri => {
  console.log('File created:', uri.fsPath);
  treeProvider.refresh();
});
Полный SKILL.md на GitHub

Установить VS Code Extension Patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл VS Code Extension Patterns?

Expert knowledge of VS Code Extension API patterns, TreeDataProvider implementation, and command registration

Как установить скилл VS Code Extension Patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл VS Code Extension Patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить VS Code Extension Patterns с