Vscode插件开发教程

文章发布时间:

最后更新时间:

文章总字数:
1.5k

预计阅读时间:
7 分钟

本教程记录一次简单的Vscode插件开发过程

清理

使用管理员权限打开命令行窗口,运行如下命令:

1
2
npm uninstall -g yo generator-code
npm cache clean --force

使用管理员权限配置环境

  1. 安装Node.js:确保你已安装最新版本的Node.js,使用以下命令验证:

    1
    2
    node -v
    npm -v

    如果未安装可按以下步骤使用官方安装包来安装node.js:

    • 卸载旧版本

      1
      npm uninstall -g npm  # 先卸载npm
    • 访问 Node.js 官网(建议选择 LTS 版本,如 20.x)。下载 .msi 安装包(如 node-v20.x.x-x64.msi)。

    • 双击安装包,全程默认选项(会自动覆盖旧版本并更新环境变量)。

    • 勾选 **Automatically install the necessary tools**(包括 npmPython 等依赖)。

    • 打开新的终端(CMD/PowerShell),运行:

      1
      2
      node -v  # 应显示新版本号(如 v20.x.x)
      npm -v # 应显示对应的npm版本
  2. 安装Yeoman和VS Code扩展生成器

    1
    npm install -g yo generator-code
    • yo:Yeoman,一个项目脚手架工具
    • generator-code:专门用于生成VSCode插件项目的生成器

创建新插件项目

  1. 运行生成器

    1
    yo code
  2. 按照提示选择:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    D:\my-vscode>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 (JavaScript)
    ? What's the name of your extension? rainbow-comments
    ? What's the identifier of your extension? rainbow-comments
    ? What's the description of your extension? rainbow-comments
    ? Enable JavaScript type checking in 'jsconfig.json'? No
    ? Initialize a git repository? Yes
    ? Which package manager to use? npm

编写插件代码

打开extension.js文件,替换为以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
const vscode = require('vscode');

// 定义多种颜色方案
const colorSchemes = {
rainbow: [ // 彩虹色
'#FF0000', '#FF7F00', '#FFFF00',
'#00FF00', '#5ec5f5ff', '#0000FF', '#9400D3'
],
pastel: [ // 糖果色
'#FFD1DC', '#FFECB8', '#E2F0CB',
'#B5EAD7', '#C7CEEA', '#D8B5FF'
],
monochrome: [ // 灰色系
'#6f6f6fff'
],
warm: [ // 暖色调
'#FF6B6B', '#FFA07A', '#FFD166',
'#F7C1BB', '#ff0080ff'
],
cool: [ // 冷色调
'#c6f4fbff', '#a39feaff', '#7BC9FF',
'#9494ffff', '#b1d8fbff'
]
};

// 清除所有装饰器
function clearAllDecorations(editor, decorationTypes) {
decorationTypes.forEach(type => {
editor.setDecorations(type, []);
});
}

/**
* 应用颜色方案到注释
* @param {vscode.TextEditor} editor
* @param {string[]} colors
*/
function applyColorScheme(editor, colors) {
const document = editor.document;
const text = document.getText();
const commentRegex = /(\/\/[^\n]*|\/\*[\s\S]*?\*\/)/g;
let match;
let colorIndex = 0;
const decorations = [];

while ((match = commentRegex.exec(text))) {
const startPos = document.positionAt(match.index);
const endPos = document.positionAt(match.index + match[0].length);

decorations.push({
range: new vscode.Range(startPos, endPos),
renderOptions: {
color: colors[colorIndex % colors.length],
fontWeight: 'bold',
fontStyle: 'italic'
}
});
colorIndex++;
}

// 创建装饰器类型并应用
const decorationTypes = colors.map(color => {
return vscode.window.createTextEditorDecorationType({
color: color,
fontWeight: 'bold',
fontStyle: 'italic'
});
});

// 应用装饰器
colors.forEach((color, index) => {
const colorDecorations = decorations.filter((d, i) => i % colors.length === index);
editor.setDecorations(decorationTypes[index], colorDecorations);
});

return decorationTypes;
}

function activate(context) {
let activeDecorationTypes = []; // 保存当前活动的装饰器

// 注册多个命令
const commands = [
{ name: 'rainbow', title: '注释颜色: 彩虹色' },
{ name: 'pastel', title: '注释颜色: 糖果色' },
{ name: 'monochrome', title: '注释颜色: 灰色' },
{ name: 'warm', title: '注释颜色: 暖色' },
{ name: 'cool', title: '注释颜色: 冷色' },
{ name: 'clear', title: '恢复默认注释颜色' }
];

commands.forEach(cmd => {
let disposable = vscode.commands.registerCommand(
`rainbow-comments.${cmd.name}`,
function () {
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showWarningMessage('没有打开的编辑器!');
return;
}

// 清除之前的装饰器
clearAllDecorations(editor, activeDecorationTypes);
activeDecorationTypes = [];

if (cmd.name !== 'clear') {
// 应用新颜色方案
activeDecorationTypes = applyColorScheme(
editor,
colorSchemes[cmd.name]
);
vscode.window.showInformationMessage(
`已应用 ${cmd.title} 方案!`
);
} else {
vscode.window.showInformationMessage('已清除所有注释颜色');
}
}
);
context.subscriptions.push(disposable);
});
}

function deactivate() {
// 清理资源
}

module.exports = {
activate,
deactivate
};

修改package.json

package.json中添加以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"contributes": {
"commands": [
{
"command": "rainbow-comments.rainbow",
"title": "注释颜色: 彩虹色"
},
{
"command": "rainbow-comments.pastel",
"title": "注释颜色: 糖果色"
},
{
"command": "rainbow-comments.monochrome",
"title": "注释颜色: 灰色"
},
{
"command": "rainbow-comments.warm",
"title": "注释颜色: 暖色"
},
{
"command": "rainbow-comments.cool",
"title": "注释颜色: 冷色"
},
{
"command": "rainbow-comments.clear",
"title": "恢复默认注释颜色"
}
],
"menus": {
"editor/context": [
{
"command": "rainbow-comments.rainbow",
"group": "rainbow@1",
"when": "editorTextFocus"
},
{
"command": "rainbow-comments.pastel",
"group": "rainbow@2",
"when": "editorTextFocus"
},
{
"command": "rainbow-comments.monochrome",
"group": "rainbow@3",
"when": "editorTextFocus"
},
{
"command": "rainbow-comments.warm",
"group": "rainbow@4",
"when": "editorTextFocus"
},
{
"command": "rainbow-comments.cool",
"group": "rainbow@5",
"when": "editorTextFocus"
},
{
"command": "rainbow-comments.clear",
"group": "rainbow@6",
"when": "editorTextFocus"
}
]
}
}

运行和测试插件

  1. 按F5启动调试
  2. 在新打开的VSCode窗口中打开一个代码文件
  3. 按Ctrl+Shift+P打开命令面板输入并选择命令
  4. 或者直接右键选择需要执行的命令
  5. 观察你的注释颜色变化

发布插件

如果你想分享你的插件:

  1. 安装vsce:npm install -g vsce
  2. 创建发布账号:https://aka.ms/vscode-create-publisher
  3. 登录:vsce login <publisher-name>
  4. 打包:vsce package
  5. 发布:vsce publish

或者你也可以:

  1. 安装vsce:npm install -g vsce
  2. 创建发布账号:https://aka.ms/vscode-create-publisher
  3. 打包:vsce package
  4. 发布:将生成的.vsix文件拖到上述网页上传 Azure DevOps 扩展中即可

注意:.vsix 文件的发布者信息必须与目标发布者相匹配,即项目中的 package.json 文件中的”publisher”: “xxx”必须与登录的发布者ID完全一致

示例

已将上述插件上传到了 vscode 中的插件应用市场,可以搜索 Zenith-zh 安装后在目标文件中右键启用后查看效果🥰

打赏
微信 | Wechat