这篇文章记录如何编写一个vscode插件(vscode extension)。
最近我刚刚编写完一个生成模板配置文件的vscode插件,记录一下经验
vscode的插件开发是有一定规范的,因此会有一个命令行工具用于生成项目结构。
参考: https://code.visualstudio.com/api/get-started/your-first-extension
npm安装项目生成工具:
npm install -g yo generator-code
使用项目生成工具生成项目:
yo code
项目可以使用typescript或者javascript编写,可以选择生成什么类型的项目。
{
"name": "hello-template",
// ...
// 这里注册用户按键ctrl+shift+p, 输入tgen, 按enter,就会执行插件逻辑
"activationEvents": [
"onCommand:hello-template.tgen"
],
// 这里启动文件是extension.js,也就是插件逻辑的主要实现点
"main": "./extension.js",
function activate(context) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "hello-template" is now active!');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
let disposable = vscode.commands.registerCommand('hello.example.tgen', function () {
//这里就是插件的逻辑主体,通常可以引用任何nodejs库
}
}
但是在这里我想特别记录几个API:
也就是配置文件生成后放的路径:
vscode.workspace.workspaceFolders[0].uri.fsPath
模板生成程序需要从插件安装目录中读取模板
vscode.extensions.getExtension("." ).extensionPath
这里的 对象package.json里的
{
"name": "cicd-template", // extension_name
"displayName": "cicd-template",
"description": "",
"publisher": "oneslideicywater", // publisher_name
}
参考链接:https://code.visualstudio.com/api/working-with-extensions/publishing-extension
也就是文档的Get a Personal Access Token部分,按照文档的步骤把token拿到。
在本地开发环境登录:
vsce login <publisher name>
先安装打包工具
npm install -g vsce
打包
# 生成-.vsix文件
vsce package
# 发布
vsce publish
注意修改package.json里的
version字段,因为每次发布必须是加版本号
插件发布到markplace,应该就可以在那看见
链接:https://marketplace.visualstudio.com/vscode