vscode-extension-builder

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

VS Code Extension Builder

VS Code 扩展构建指南

Build professional VS Code extensions with proper architecture, best practices, and complete tooling support.
通过合理的架构、最佳实践和完整的工具支持,构建专业的VS Code扩展。

Quick Start

快速开始

For immediate extension creation:
  1. Initialize: Run
    npx --package yo --package generator-code -- yo code
  2. Choose type: New Extension (TypeScript)
  3. Fill details: Name, identifier, description
  4. Develop: Open in VS Code, press F5 to debug
  5. Test: Run commands in Extension Development Host
  6. Package: Run
    vsce package
    when ready
For detailed guidance, follow the workflow below.
如需立即创建扩展:
  1. 初始化:运行
    npx --package yo --package generator-code -- yo code
  2. 选择类型:New Extension (TypeScript)(TypeScript 新扩展)
  3. 填写详情:名称、标识符、描述
  4. 开发:在VS Code中打开项目,按F5进行调试
  5. 测试:在扩展开发宿主中运行命令
  6. 打包:准备就绪后运行
    vsce package
如需详细指导,请遵循以下工作流程。

Extension Types

扩展类型

Choose the type that matches your needs:
  • Command Extension: Add commands to Command Palette (simplest, most common)
  • Language Support: Syntax highlighting, IntelliSense, formatting
  • Webview Extension: Custom UI panels with HTML/CSS/JS
  • Tree View: Custom sidebar views with hierarchical data
  • Debugger: Add debugging support for languages
  • Theme: Color themes, file icon themes
  • Snippet Provider: Code snippets for languages
选择符合你需求的类型:
  • 命令扩展:向命令面板添加命令(最简单、最常用)
  • 语言支持扩展:语法高亮、智能提示、代码格式化
  • 网页视图扩展:使用HTML/CSS/JS构建自定义UI面板
  • 树形视图扩展:带有层级数据的自定义侧边栏视图
  • 调试器扩展:为语言添加调试支持
  • 主题扩展:颜色主题、文件图标主题
  • 代码片段提供器:为语言提供代码片段

Core Workflow

核心工作流程

1. Gather Requirements

1. 收集需求

Ask user about:
  • Purpose: What should the extension do?
  • Type: Which extension type? (command, language, webview, etc.)
  • Features: Specific functionality needed
  • UI: Commands, views, panels, status bar items?
  • Activation: When should it activate?
向用户确认以下内容:
  • 用途:扩展需要实现什么功能?
  • 类型:选择哪种扩展类型?(命令、语言、网页视图等)
  • 功能:需要的具体功能
  • UI:是否需要命令、视图、面板、状态栏项?
  • 激活时机:扩展应在何时激活?

2. Choose Extension Type & Architecture

2. 选择扩展类型与架构

Based on requirements, select appropriate pattern:
Simple Command Extension (most common):
  • Single responsibility
  • Command Palette integration
  • Quick to build
Language Extension:
  • Syntax highlighting (TextMate grammar)
  • Language server for IntelliSense
  • Complex but powerful
Webview Extension:
  • Custom UI needed
  • Rich interactions
  • More complex state management
See extension-anatomy.md for detailed structure.
根据需求选择合适的模式:
简单命令扩展(最常用):
  • 单一职责
  • 集成命令面板
  • 开发快速
语言扩展
  • 语法高亮(TextMate语法)
  • 用于智能提示的语言服务器
  • 复杂度高但功能强大
网页视图扩展
  • 需要自定义UI
  • 丰富的交互能力
  • 状态管理更复杂
如需详细结构说明,请查看 extension-anatomy.md

3. Initialize Project

3. 初始化项目

Option A: Use Yeoman Generator (Recommended)
bash
npx --package yo --package generator-code -- yo code
Fill in:
  • Type: New Extension (TypeScript)
  • Name: User-friendly name
  • Identifier: lowercase-with-hyphens
  • Description: Clear purpose
  • Git: Yes
  • Bundler: esbuild (recommended) or webpack
  • Package manager: npm
Option B: Use Templates
For specific patterns, copy from
assets/templates/
:
  • command-extension/
    - Command-based extension
  • language-support/
    - Language extension starter
  • webview-extension/
    - Webview-based extension
选项A:使用Yeoman生成器(推荐)
bash
npx --package yo --package generator-code -- yo code
填写以下信息:
  • 类型:New Extension (TypeScript)(TypeScript 新扩展)
  • 名称:用户友好的名称
  • 标识符:小写连字符格式(lowercase-with-hyphens)
  • 描述:清晰的用途说明
  • Git:是
  • 打包工具:esbuild(推荐)或webpack
  • 包管理器:npm
选项B:使用模板
针对特定模式,可从
assets/templates/
复制:
  • command-extension/
    - 基于命令的扩展
  • language-support/
    - 语言扩展启动模板
  • webview-extension/
    - 基于网页视图的扩展

4. Implement Core Functionality

4. 实现核心功能

For Command Extensions:
  1. Define command in
    package.json
    :
json
{
  "contributes": {
    "commands": [{
      "command": "extension.commandId",
      "title": "Command Title"
    }]
  }
}
  1. Register command in
    extension.ts
    :
typescript
export function activate(context: vscode.ExtensionContext) {
  let disposable = vscode.commands.registerCommand('extension.commandId', () => {
    vscode.window.showInformationMessage('Hello from Extension!');
  });
  context.subscriptions.push(disposable);
}
For Language Extensions: See common-apis.md for language features APIs.
For Webview Extensions: See common-apis.md for webview creation patterns.
命令扩展实现步骤:
  1. package.json
    中定义命令:
json
{
  "contributes": {
    "commands": [{
      "command": "extension.commandId",
      "title": "Command Title"
    }]
  }
}
  1. extension.ts
    中注册命令:
typescript
export function activate(context: vscode.ExtensionContext) {
  let disposable = vscode.commands.registerCommand('extension.commandId', () => {
    vscode.window.showInformationMessage('Hello from Extension!');
  });
  context.subscriptions.push(disposable);
}
语言扩展实现: 请查看 common-apis.md 了解语言功能API。
网页视图扩展实现: 请查看 common-apis.md 了解网页视图创建模式。

5. Configure Activation & Contributions

5. 配置激活事件与贡献点

Activation Events determine when your extension loads:
  • onCommand
    : When command is invoked
  • onLanguage
    : When file type opens
  • onView
    : When tree view becomes visible
  • *
    : On startup (avoid if possible)
See activation-events.md for complete reference.
Contributions declare extension capabilities in
package.json
:
  • commands
    : Command Palette entries
  • menus
    : Context menu items
  • keybindings
    : Keyboard shortcuts
  • languages
    : Language support
  • views
    : Tree views
  • configuration
    : Settings
激活事件决定扩展的加载时机:
  • onCommand
    :当命令被调用时
  • onLanguage
    :当打开指定类型文件时
  • onView
    :当树形视图可见时
  • *
    :启动时加载(尽可能避免使用)
完整参考请查看 activation-events.md
贡献点
package.json
中声明扩展的能力:
  • commands
    :命令面板条目
  • menus
    :上下文菜单项
  • keybindings
    :键盘快捷键
  • languages
    :语言支持
  • views
    :树形视图
  • configuration
    :设置项

6. Test & Debug

6. 测试与调试

Local Testing:
  1. Press
    F5
    in VS Code to launch Extension Development Host
  2. Test commands and features
  3. Check Debug Console for logs
  4. Set breakpoints for debugging
Automated Testing:
  • Unit tests: Test business logic
  • Integration tests: Test VS Code API interactions
  • Use
    @vscode/test-electron
    for testing
Common Issues:
  • Command not appearing: Check
    contributes.commands
    and activation events
  • Extension not activating: Verify activation events in
    package.json
  • API errors: Check VS Code API version compatibility
本地测试:
  1. 在VS Code中按
    F5
    启动扩展开发宿主
  2. 测试命令与功能
  3. 在调试控制台查看日志
  4. 设置断点进行调试
自动化测试:
  • 单元测试:测试业务逻辑
  • 集成测试:测试VS Code API交互
  • 使用
    @vscode/test-electron
    进行测试
常见问题:
  • 命令未显示:检查
    contributes.commands
    和激活事件
  • 扩展未激活:验证
    package.json
    中的激活事件
  • API错误:检查VS Code API版本兼容性

7. Package & Distribute

7. 打包与分发

Prepare for Publishing:
  1. Update README.md with features and usage
  2. Add extension icon (128x128 PNG)
  3. Set repository URL in package.json
  4. Add LICENSE file
  5. Test thoroughly
Package Extension:
bash
npm install -g @vscode/vsce
vsce package
Creates
.vsix
file for distribution.
Publish to Marketplace:
bash
vsce publish
Requires Azure DevOps personal access token.
发布准备:
  1. 更新README.md,添加功能说明与使用方法
  2. 添加扩展图标(128x128 PNG格式)
  3. 在package.json中设置仓库URL
  4. 添加LICENSE文件
  5. 全面测试
打包扩展:
bash
npm install -g @vscode/vsce
vsce package
生成用于分发的
.vsix
文件。
发布到市场:
bash
vsce publish
需要Azure DevOps个人访问令牌。

Common Patterns

常见模式

Pattern 1: Simple Command

模式1:简单命令

Quick command that shows information:
typescript
vscode.commands.registerCommand('extension.showInfo', () => {
  vscode.window.showInformationMessage('Information message');
});
显示信息的快速命令:
typescript
vscode.commands.registerCommand('extension.showInfo', () => {
  vscode.window.showInformationMessage('Information message');
});

Pattern 2: Command with User Input

模式2:带用户输入的命令

Get input before executing:
typescript
vscode.commands.registerCommand('extension.greet', async () => {
  const name = await vscode.window.showInputBox({
    prompt: 'Enter your name'
  });
  if (name) {
    vscode.window.showInformationMessage(`Hello, ${name}!`);
  }
});
执行前获取用户输入:
typescript
vscode.commands.registerCommand('extension.greet', async () => {
  const name = await vscode.window.showInputBox({
    prompt: 'Enter your name'
  });
  if (name) {
    vscode.window.showInformationMessage(`Hello, ${name}!`);
  }
});

Pattern 3: File Operation Command

模式3:文件操作命令

Work with active editor:
typescript
vscode.commands.registerCommand('extension.processFile', () => {
  const editor = vscode.window.activeTextEditor;
  if (!editor) {
    vscode.window.showErrorMessage('No active editor');
    return;
  }
  
  const document = editor.document;
  const text = document.getText();
  // Process text...
});
处理活动编辑器:
typescript
vscode.commands.registerCommand('extension.processFile', () => {
  const editor = vscode.window.activeTextEditor;
  if (!editor) {
    vscode.window.showErrorMessage('No active editor');
    return;
  }
  
  const document = editor.document;
  const text = document.getText();
  // 处理文本...
});

Pattern 4: Status Bar Item

模式4:状态栏项

Show persistent status:
typescript
const statusBarItem = vscode.window.createStatusBarItem(
  vscode.StatusBarAlignment.Right,
  100
);
statusBarItem.text = "$(check) Ready";
statusBarItem.show();
context.subscriptions.push(statusBarItem);
显示持久化状态:
typescript
const statusBarItem = vscode.window.createStatusBarItem(
  vscode.StatusBarAlignment.Right,
  100
);
statusBarItem.text = "$(check) Ready";
statusBarItem.show();
context.subscriptions.push(statusBarItem);

Reference Navigation

参考导航

Load these references as needed:
  • extension-anatomy.md: When you need details about:
    • Extension structure and file organization
    • package.json
      manifest fields
    • Entry point and lifecycle hooks
    • Extension context and disposables
  • common-apis.md: When implementing:
    • Window and editor operations
    • Workspace and file system access
    • Language features (IntelliSense, diagnostics)
    • Webview creation and messaging
    • Tree views and custom UI
  • activation-events.md: When configuring:
    • When extension should load
    • Performance optimization
    • Lazy loading strategies
  • best-practices.md: When considering:
    • UX guidelines and design patterns
    • Performance optimization
    • Security considerations
    • Testing strategies
    • Publishing guidelines
根据需要加载以下参考文档:
  • extension-anatomy.md:当你需要了解以下内容时:
    • 扩展结构与文件组织
    • package.json
      清单字段
    • 入口点与生命周期钩子
    • 扩展上下文与可释放资源
  • common-apis.md:当你实现以下功能时:
    • 窗口与编辑器操作
    • 工作区与文件系统访问
    • 语言功能(智能提示、诊断)
    • 网页视图创建与消息传递
    • 树形视图与自定义UI
  • activation-events.md:当你配置以下内容时:
    • 扩展加载时机
    • 性能优化
    • 懒加载策略
  • best-practices.md:当你考虑以下内容时:
    • UX指南与设计模式
    • 性能优化
    • 安全注意事项
    • 测试策略
    • 发布指南

Key Principles

核心原则

Performance

性能

  • Lazy load: Use specific activation events, not
    *
  • Async operations: Use async/await for I/O
  • Dispose resources: Clean up subscriptions
  • Minimize startup: Defer heavy operations
  • 懒加载:使用特定的激活事件,而非
    *
  • 异步操作:对I/O操作使用async/await
  • 释放资源:清理订阅资源
  • 最小化启动开销:延迟执行重操作

User Experience

用户体验

  • Clear commands: Descriptive titles and categories
  • Feedback: Show progress for long operations
  • Error handling: Helpful error messages
  • Consistent UI: Follow VS Code conventions
  • 清晰的命令:描述性标题与分类
  • 反馈机制:为长操作显示进度
  • 错误处理:提供有帮助的错误消息
  • 一致的UI:遵循VS Code设计规范

Code Quality

代码质量

  • TypeScript: Use strict mode for type safety
  • Error handling: Try-catch for all operations
  • Logging: Use console.log for debugging
  • Testing: Write tests for critical functionality
  • TypeScript:使用严格模式保证类型安全
  • 错误处理:对所有操作使用try-catch
  • 日志记录:使用console.log进行调试
  • 测试:为关键功能编写测试

Troubleshooting

故障排除

Extension Not Appearing

扩展未显示

  • Verify
    package.json
    syntax (valid JSON)
  • Check
    main
    field points to compiled output
  • Ensure activation events are correct
  • Reload window:
    Developer: Reload Window
  • 验证
    package.json
    语法(有效的JSON)
  • 检查
    main
    字段指向编译后的输出文件
  • 确保激活事件配置正确
  • 重新加载窗口:执行
    Developer: Reload Window

Command Not Working

命令无法工作

  • Check command ID matches in
    package.json
    and code
  • Verify activation event includes the command
  • Check Debug Console for errors
  • Ensure command is registered in
    activate()
  • 检查
    package.json
    与代码中的命令ID是否匹配
  • 验证激活事件包含该命令
  • 在调试控制台查看错误信息
  • 确保命令在
    activate()
    中注册

Build Errors

构建错误

  • Run
    npm install
    to install dependencies
  • Check TypeScript configuration
  • Verify VS Code API version compatibility
  • Update
    @types/vscode
    if needed
  • 运行
    npm install
    安装依赖
  • 检查TypeScript配置
  • 验证VS Code API版本兼容性
  • 如有需要更新
    @types/vscode

Examples by Use Case

按使用场景分类的示例

Add Command to Format Code

添加代码格式化命令

  1. Type: Command extension
  2. Activation:
    onCommand
  3. Implementation: Get editor text, format, replace
  4. UI: Command Palette entry
  1. 类型:命令扩展
  2. 激活事件:
    onCommand
  3. 实现:获取编辑器文本、格式化、替换
  4. UI:命令面板条目

Add Syntax Highlighting

添加语法高亮

  1. Type: Language extension
  2. Activation:
    onLanguage:mylang
  3. Implementation: TextMate grammar in JSON
  4. UI: Automatic on file open
  1. 类型:语言支持扩展
  2. 激活事件:
    onLanguage:mylang
  3. 实现:JSON格式的TextMate语法
  4. UI:打开文件时自动生效

Add Custom Sidebar View

添加自定义侧边栏视图

  1. Type: Tree view extension
  2. Activation:
    onView:myView
  3. Implementation: TreeDataProvider interface
  4. UI: Activity bar icon + sidebar panel
  1. 类型:树形视图扩展
  2. 激活事件:
    onView:myView
  3. 实现:TreeDataProvider接口
  4. UI:活动栏图标 + 侧边栏面板

Add Quick Pick Menu

添加快速选择菜单

  1. Type: Command extension with UI
  2. Activation:
    onCommand
  3. Implementation:
    showQuickPick
    with items
  4. UI: Searchable dropdown menu
  1. 类型:带UI的命令扩展
  2. 激活事件:
    onCommand
  3. 实现:使用
    showQuickPick
    展示选项
  4. UI:可搜索的下拉菜单

Resources in This Skill

本技能包含的资源

Related Skills

相关技能

For code quality and architecture review of your extension code:
  • detect-code-smells
    : Check extension code quality
  • security-pattern-check
    : Security review for extensions
  • suggest-performance-fix
    : Optimize extension performance
如需对扩展代码进行代码质量与架构审查:
  • detect-code-smells
    :检查扩展代码质量
  • security-pattern-check
    :扩展安全审查
  • suggest-performance-fix
    :优化扩展性能

Notes

注意事项

This skill provides the complete workflow for VS Code extension development, from initial concept to published extension. Use progressive disclosure: start with Quick Start for simple cases, dive into references for complex requirements. Templates in
assets/
provide copy-paste starting points for common patterns.
本技能提供了从初始概念到发布的完整VS Code扩展开发工作流程。采用渐进式展示:简单场景使用快速开始,复杂需求深入参考文档。
assets/
中的模板为常见模式提供了可直接复制使用的起点。