开发环境准备
1. 通过npm全局安装 yo generator-code
npm install -g yo generator-code
2. VSCode 安装 esbuild-problem-matchers 插件
marketplace.visualstudio.com/items?itemN…
新建插件项目
yo code
选择 New Extension (TypeScript), 并选择esbuild作为打包工具
最后生成的项目
package.json文件说明
{
"name": "my-extension", // 作者名称
"displayName": "my-extension", // 插件名称
"description": "我的插件描述", // 插件描述
"version": "0.0.1", // 版本
"engines": {
"vscode": "^1.87.0"
},
"categories": [
"Other"
],
"activationEvents": [], // 激活事件, 使用*表示任何语言都能激活。或者指定激活事件"onLanguage:plaintext"、"onLanguage:javascript"
"main": "./out/extension.js", // 插件激活入口
"contributes": {
"commands": [ // 命令
{
"command": "my-extension.helloWorld",
"title": "我的命令名称:Hello World"
}
]
},
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"pretest": "npm run compile && npm run lint",
"lint": "eslint src --ext ts",
"test": "vscode-test"
},
"devDependencies": {
"@types/vscode": "^1.87.0",
"@types/mocha": "^10.0.6",
"@types/node": "18.x",
"@typescript-eslint/eslint-plugin": "^7.4.0",
"@typescript-eslint/parser": "^7.4.0",
"eslint": "^8.57.0",
"typescript": "^5.3.3",
"@vscode/test-cli": "^0.0.8",
"@vscode/test-electron": "^2.3.9"
}
}
extension.ts 文件说明
// 'vscode' 模块包含 VS Code 扩展性 API
// 导入模块并在下面的代码中使用别名 vscode 引用它
import * as vscode from 'vscode';
// 当您的扩展被激活时调用此方法
// 您的扩展在第一次执行命令时被激活
export function activate(context: vscode.ExtensionContext) {
// ---开发插件的时候,会输出在 “调试控制台”---
// 使用控制台输出诊断信息 (console.log) 和错误 (console.error)
// 这行代码只会在扩展激活时执行一次
console.log('恭喜,您的扩展 "run-tsx" 现在已激活!');
// ---注册运行文件命令---
// 命令已在 package.json 文件中定义
// 现在使用 registerCommand 提供命令的实现
// commandId 参数必须与 package.json 中的 command 字段匹配
const helloWorldDisposable = vscode.commands.registerCommand('run-tsx.helloWorld', () => {
// 您在此处放置的代码将在每次执行命令时执行
// 向用户显示消息框
vscode.window.showInformationMessage('Hello World from Run Tsx!');
});
context.subscriptions.push(helloWorldDisposable);
}
// 当您的扩展被停用时调用此方法
export function deactivate() {}
调试
- 执行命令:
pnpm run compile, 将ts编译为js - 切换到
运行和调试面板,修改launch.json文件
{
"version": "0.2.0",
"configurations": [
{
"name": "Run Extension",
"type": "extensionHost",
"request": "launch",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--disable-extensions" // 可选:禁用其他插件
],
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"preLaunchTask": "${defaultBuildTask}"
}
]
}
- 切换到
运行和调试面板,在该面板按F5, 会打开[扩展开发宿主]Visual Studio Code这个VSCode新窗口,你就可以在这个新窗口中调试你的插件了
插件注册右键菜单
在 package.json 中定义
{
"name": "run-tsx",
// ...
"contributes": {
"commands": [
{
"command": "run-tsx.helloWorld",
"title": "运行Run Tsx的helloWorld命令"
}
],
"menus": {
"explorer/context": [ // 右键文件列表的时候
{
"command": "run-tsx.helloWorld",
"when": "resourceExtname == .ts || resourceExtname == .tsx",
"group": "navigation@1"
}
],
"editor/context": [ // 右键文本内容的时候
{
"command": "run-tsx.helloWorld",
"when": "resourceExtname == .ts || resourceExtname == .tsx",
"group": "navigation@1"
}
]
}
},
}