vscode-extension-builder
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseVS 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:
- Initialize: Run
npx --package yo --package generator-code -- yo code - Choose type: New Extension (TypeScript)
- Fill details: Name, identifier, description
- Develop: Open in VS Code, press F5 to debug
- Test: Run commands in Extension Development Host
- Package: Run when ready
vsce package
For detailed guidance, follow the workflow below.
如需立即创建扩展:
- 初始化:运行
npx --package yo --package generator-code -- yo code - 选择类型:New Extension (TypeScript)(TypeScript 新扩展)
- 填写详情:名称、标识符、描述
- 开发:在VS Code中打开项目,按F5进行调试
- 测试:在扩展开发宿主中运行命令
- 打包:准备就绪后运行
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 codeFill 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-based extension
command-extension/ - - Language extension starter
language-support/ - - Webview-based extension
webview-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:
- Define command in :
package.json
json
{
"contributes": {
"commands": [{
"command": "extension.commandId",
"title": "Command Title"
}]
}
}- 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.
命令扩展实现步骤:
- 在 中定义命令:
package.json
json
{
"contributes": {
"commands": [{
"command": "extension.commandId",
"title": "Command Title"
}]
}
}- 在 中注册命令:
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:
- : When command is invoked
onCommand - : When file type opens
onLanguage - : When tree view becomes visible
onView - : On startup (avoid if possible)
*
See activation-events.md for complete reference.
Contributions declare extension capabilities in :
package.json- : Command Palette entries
commands - : Context menu items
menus - : Keyboard shortcuts
keybindings - : Language support
languages - : Tree views
views - : Settings
configuration
激活事件决定扩展的加载时机:
- :当命令被调用时
onCommand - :当打开指定类型文件时
onLanguage - :当树形视图可见时
onView - :启动时加载(尽可能避免使用)
*
完整参考请查看 activation-events.md。
贡献点在 中声明扩展的能力:
package.json- :命令面板条目
commands - :上下文菜单项
menus - :键盘快捷键
keybindings - :语言支持
languages - :树形视图
views - :设置项
configuration
6. Test & Debug
6. 测试与调试
Local Testing:
- Press in VS Code to launch Extension Development Host
F5 - Test commands and features
- Check Debug Console for logs
- Set breakpoints for debugging
Automated Testing:
- Unit tests: Test business logic
- Integration tests: Test VS Code API interactions
- Use for testing
@vscode/test-electron
Common Issues:
- Command not appearing: Check and activation events
contributes.commands - Extension not activating: Verify activation events in
package.json - API errors: Check VS Code API version compatibility
本地测试:
- 在VS Code中按 启动扩展开发宿主
F5 - 测试命令与功能
- 在调试控制台查看日志
- 设置断点进行调试
自动化测试:
- 单元测试:测试业务逻辑
- 集成测试:测试VS Code API交互
- 使用 进行测试
@vscode/test-electron
常见问题:
- 命令未显示:检查 和激活事件
contributes.commands - 扩展未激活:验证 中的激活事件
package.json - API错误:检查VS Code API版本兼容性
7. Package & Distribute
7. 打包与分发
Prepare for Publishing:
- Update README.md with features and usage
- Add extension icon (128x128 PNG)
- Set repository URL in package.json
- Add LICENSE file
- Test thoroughly
Package Extension:
bash
npm install -g @vscode/vsce
vsce packageCreates file for distribution.
.vsixPublish to Marketplace:
bash
vsce publishRequires Azure DevOps personal access token.
发布准备:
- 更新README.md,添加功能说明与使用方法
- 添加扩展图标(128x128 PNG格式)
- 在package.json中设置仓库URL
- 添加LICENSE文件
- 全面测试
打包扩展:
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
- manifest fields
package.json - 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 syntax (valid JSON)
package.json - Check field points to compiled output
main - Ensure activation events are correct
- Reload window:
Developer: Reload Window
- 验证 语法(有效的JSON)
package.json - 检查 字段指向编译后的输出文件
main - 确保激活事件配置正确
- 重新加载窗口:执行
Developer: Reload Window
Command Not Working
命令无法工作
- Check command ID matches in and code
package.json - Verify activation event includes the command
- Check Debug Console for errors
- Ensure command is registered in
activate()
- 检查 与代码中的命令ID是否匹配
package.json - 验证激活事件包含该命令
- 在调试控制台查看错误信息
- 确保命令在 中注册
activate()
Build Errors
构建错误
- Run to install dependencies
npm install - Check TypeScript configuration
- Verify VS Code API version compatibility
- Update if needed
@types/vscode
- 运行 安装依赖
npm install - 检查TypeScript配置
- 验证VS Code API版本兼容性
- 如有需要更新
@types/vscode
Examples by Use Case
按使用场景分类的示例
Add Command to Format Code
添加代码格式化命令
- Type: Command extension
- Activation:
onCommand - Implementation: Get editor text, format, replace
- UI: Command Palette entry
- 类型:命令扩展
- 激活事件:
onCommand - 实现:获取编辑器文本、格式化、替换
- UI:命令面板条目
Add Syntax Highlighting
添加语法高亮
- Type: Language extension
- Activation:
onLanguage:mylang - Implementation: TextMate grammar in JSON
- UI: Automatic on file open
- 类型:语言支持扩展
- 激活事件:
onLanguage:mylang - 实现:JSON格式的TextMate语法
- UI:打开文件时自动生效
Add Custom Sidebar View
添加自定义侧边栏视图
- Type: Tree view extension
- Activation:
onView:myView - Implementation: TreeDataProvider interface
- UI: Activity bar icon + sidebar panel
- 类型:树形视图扩展
- 激活事件:
onView:myView - 实现:TreeDataProvider接口
- UI:活动栏图标 + 侧边栏面板
Add Quick Pick Menu
添加快速选择菜单
- Type: Command extension with UI
- Activation:
onCommand - Implementation: with items
showQuickPick - UI: Searchable dropdown menu
- 类型:带UI的命令扩展
- 激活事件:
onCommand - 实现:使用 展示选项
showQuickPick - UI:可搜索的下拉菜单
Resources in This Skill
本技能包含的资源
- references/: Detailed documentation (load as needed)
- assets/templates/: Starting templates for common patterns
- Official docs: https://code.visualstudio.com/api
- references/:详细文档(按需加载)
- assets/templates/:常见模式的启动模板
- 官方文档:https://code.visualstudio.com/api
Related Skills
相关技能
For code quality and architecture review of your extension code:
- : Check extension code quality
detect-code-smells - : Security review for extensions
security-pattern-check - : Optimize extension performance
suggest-performance-fix
如需对扩展代码进行代码质量与架构审查:
- :检查扩展代码质量
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 provide copy-paste starting points for common patterns.
assets/本技能提供了从初始概念到发布的完整VS Code扩展开发工作流程。采用渐进式展示:简单场景使用快速开始,复杂需求深入参考文档。 中的模板为常见模式提供了可直接复制使用的起点。
assets/