环境准备
Visual Studio CodeNode.jsYeoman和VS Code Extension Generatornpm install -g yo generator-codeYeoman:现代化前端项目的脚手架工具,用于生成包含指定框架结构的工程化目录结构generator-code:VS Code 插件模板
创建
- 命令行中输入
yo code,根据自己的需求,初始化项目
yo code
_-----_ ╭──────────────────────────╮
| | │ Welcome to the Visual │
|--(o)--| │ Studio Code Extension │
`---------´ │ generator! │
( _´U`_ ) ╰──────────────────────────╯
/___A___\ /
| ~ |
__'.___.'__
´ ` |° ´ Y `
? What type of extension do you want to create? New Extension (TypeScript)
? What's the name of your extension? myFirstExtension
? What's the identifier of your extension? myfirstextension
? What's the description of your extension? My First Extension
? Initialize a git repository? Yes
? Bundle the source code with webpack? Yes
? Which package manager to use? yarn
code ./myfirstextension
- 初始化后项目,按
F5启动调试,看到一个插件窗口 - 在命令面板(
Ctrl+Shift+P) 中输入Hello World命令,就可以看到
- 当然也支持打断点进行调试,就像平时用
VS Code调试一样
项目目录结构说明
.vscode / launch.json
用于 VS Code 调试
package.json
插件配置清单
name、publisher:vs code使用<publisher>.<name>作为插件的唯一ID;VS Code使用ID来区分各个不同的插件activationEvents:激活插件命令的事件,定义命令在何种情况下被激活(默认情况下,不会被激活)*: 只要VS Code启动,插件就会被触发,尽量少用这种事件,除非必要onCommand:命令面板中触发- 其余事件可参考:Activation Events
contributes:定义插件的各种扩展功能commands:配置命令的icon、类别、在哪里生效等;默认是在命令面板中生效的,也可以通过when字段改变- 具体配置项可参考:Contribution Points
main:入口文件engines.vscode:描述了这个插件依赖的最低VS Code api的最小版本postinstall脚本: 如果你的engines.vscode声明的是1.25版的VS Code API,那它就会按照这个声明去安装目标版本。一旦vscode.d.ts文件存在于node_modules/vscode/vscode.d.ts,IntelliSense就会开始运作,你就可以对所有VS Code API进行定义跳转或者语法检查了
extension.ts
插件入口文件
activate:当插件被激活后,会执行此函数deactivate:当插件失效(如被禁用)时,会执行此函数
vscode 模块包含了一个位于 node ./node_modules/vscode/bin/install 的脚本,这个脚本会拉取 package.json 中engines.vscode 字段定义的 VS Code API
// 加载对应版本的 VS Code API
import * as vscode from 'vscode';
// 当插件首次被激活时
export function activate(context: vscode.ExtensionContext) {
// 注册 myfirstextension.helloWorld 命令
let disposable = vscode.commands.registerCommand('myfirstextension.helloWorld', () => {
// 当该命令被触发时,就会触发以下事件
vscode.window.showInformationMessage('Hello World from myFirstExtension!');
});
context.subscriptions.push(disposable);
}
// 当插件失效(如被禁用)时,执行此函数
export function deactivate() {}
实现你的第一个插件
按照上述步骤初始化后,我们开始来写第一个插件,在命令面板中添加一个 Say Hello 命令,使其显示 Hello World! 弹窗
- 在
package.json进行配置- 在
activationEvents中定义插件命令激活的事件onCommand - 在
contributes.commands中对命令进行配置
- 在
// package.json
{
// ...
"activationEvents": [
"onCommand:test.sayHello", // onCommand 后面对应的是命令 id
],
"contributes": {
"commands": {
"command": "test.sayHello",
"title": "Say Hello" // 插件名字
}
}
}
- 在
extension.ts中通过vscode.commands.registerCommand注册命令
// extension.ts
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('test.sayHello', () => {
vscode.window.showInformationMessage('Hello World!');
});
context.subscriptions.push(disposable);
}
export function deactivate() {}