一起来了解 VS Code 插件开发

1,384 阅读4分钟

作为前端开发,VS Code大家都有所了解,拥有丰富的插件市场,活跃的社区。在开发过程中,大家都会安装一些实用的插件,来提高工作效率,何不自己开发一个插件试试呢,可以清楚的知道插件的开发、发布、更新等流程,对VS Code加深认识,接下来开始探索之旅。

创建一个项目

hello world

初始化一个新项目,从 Hello World 开始,首先你需要安装一下脚手架工具

  • Yeoman Yeamon是一个前端构建工具,提供了一个构建生态系统,主要通过 yo 这个命令来构建一个完整的项目或者项目的一部分。
  • VS Code Extension Generator VS Code编写的 Yeoman 生成器,作为大多数扩展/自定义类型添加的模板。
npm install -g yo generator-code

执行命令后,安装成功后,运行一下命令生成项目

yo code

? What type of extension do you want to create? New Extension (TypeScript) // 选择你想要开发的插件类型
? What's the name of your extension? HelloWorld // 插件名称
? What's the identifier of your extension? helloworld // 插件标识符,如package.json中的name
? What's the description of your extension? test extension // 插件描述
? Initialize a git repository? Yes // 初始化git仓库
? Bundle the source code with webpack? Yes // 用webpack打包源码
? Which package manager to use? npm // 选择包管理工具

image.png

打开VS Code,点击运行插件

image.png

image.png

此时会打开一个开发调试的窗口,在命令面板(Ctrl+Shift+P)中输入Hello World命令,并选择,会在右下角输出Hello World from HelloWorld!信息,恭喜你已经运行成功。

image.png

恭喜你已经运行成功,在开发自己的功能之前,需要了解,最核心的两个文件是package.jsonextension.ts。下面将对这两个文件进行详细的介绍:

package.json

这个是插件的配置文件

{
    "name": "helloworld", // 插件名称
    "displayName": "HelloWorld", // 应用市场中展示的名称
    "description": "test extension",
    "icon": "images/logo.png", // 应用图标
    "version": "0.0.1", // 插件版本
    "engines": { // 兼容版本,如"^1.62.0" 表明最小兼容"1.62.0"版本的VS Code。
	"vscode": "^1.62.0"
    },
    "categories": [ // 插件分类
	"Other"
    ],
    "activationEvents": [ // 激活事件数组
        "onCommand:helloworld.helloWorld"
    ],
    "main": "./dist/extension.js", // 入口文件
    "contributes": { // 描述插件发布内容的对象
	"commands": [ // 配置输入命令
	    {
		"command": "helloworld.helloWorld",
		"title": "Hello World"
	    }
	],
        "keybindings": [ // 配置快捷键
          {
            "when": "editorTextFocus", // 触发条件
            "command": "helloworld.helloWorld",
            "key": "shift+alt+h"
          }
        ]
     },
     "scripts": {
	 ......
     },
     "devDependencies": {
	......
     }
}

更多配置请点击此处

extension.ts

这个是插件的入口文件,功能需要写在此文件中。其中包括两个函数

  • activate 当你的插件被激活时会调用这个方法,在第一次执行命令时被激活。
export function activate(context: vscode.ExtensionContext) {
    console.log('Congratulations, your extension "helloworld" is now active!');
    
    // 该命令已经在 package.json 文件中定义
    // 使用 registerCommand 提供命令的实现
    // commandId 参数必须与 package.json 中的 command 字段匹配
    let disposable = vscode.commands.registerCommand('helloworld.helloWorld', () => {
        vscode.window.showInformationMessage('Hello World from HelloWorld!');
    });
        
    context.subscriptions.push(disposable);
}

我们看到的提示信息就写在这里,这也就是一个简单插件注册的全过程:

1、在package.json中配置activationEvents,以及contributes,保持事件名称一致,如"helloworld.helloWorld"

2、在active函数中通过方法注册此事件vscode.commands.registerCommand('helloworld.helloWorld')

3、在命令面板(Ctrl+Shift+P)中输入Hello World命令就是contributes中配置的title,或者按绑定的快捷键,激活事件,触发回调方法

  • deactivate 当你的扩展被停用时会调用这个方法。

更多的API点击此处

实例分析

选中变量名,跳转到浏览器查询

import * as open from "open";

// 打开浏览器
const openBrowser = (url: string, query?: string) => {
  if (query) {
    open(encodeURI(url.replace(/{query}/, query)));
  } else {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
      return;
    }
    const selection = editor.selection;
    const text = editor.document.getText(selection);
    open(encodeURI(url.replace(/{query}/, text ?? "")));
  }
};

选中变量名,添加打印日志

const addConsole = () => {
  // 获取编辑器
  const editor = vscode.window.activeTextEditor;
  if (editor) {
      const selection = editor.selection;
      const text = editor.document.getText(selection);
      // 插入下一行
      vscode.commands
        .executeCommand("editor.action.insertLineAfter")
        .then(() => {
          const afterSelection = editor.selection;
          const range = new vscode.Range(
            afterSelection.start,
            afterSelection.end
          );
          editor.edit((editBuilder) => {
            editBuilder.replace(
              range,
              text ? `console.log('${text}: ', ${text});` : "console.log();"
            );
          });
        });
    }
};

再按照上述插件注册过程,即可实现对应功能。

打包发布

此时,需要安装vscode提供的发布工具vsce,它会帮助我们直接打包、发布插件至插件市场

npm install -g vsce

// 插件打包生成vsix文件,如helloworld-0.0.1.vsix
vsce package

打包前记得修改README.md等文件,补充插件描述等信息,否着会提示错误信息

推荐两种发布方式

  • 打包生成vsix插件,自行安装使用

image.png

  • 打包生成vsix插件,发布到应用市场

1、创建一个Azure DevOps 组织,注册账号

image.png

2、登录成功后,进入如下界面,获取Personal Access Token

image.png

image.png

点击Create,你就会看到新创建的Personal Access Token了,复制好。

3、创建发布者,每个插件的package.json文件都包含着publisher字段。

image.png

image.png

4、通过vsce,登录并发布插件,此时需要验证Personal Access Token

// 登录
vsce login (publisher name)

// 发布
vsce publish (version)

5、发布成功后,你可以在市场中看到插件的发布状态,等待验证成功,就可以搜到自己的插件了。

image.png

自研插件

你可以尝试一下,不喜欢请您果断卸载。。。

image.png

如果你想找一些其他提高效率VS Code插件

VS Code必备前端插件,你值得拥有!