从0-1开发一个属于自己的VS Code插件

580 阅读2分钟

搭建环境

node -v
git --version

安装好后,安装开发插件所需的依赖

npm install -g yo generator-code // 构建开发插件的基本框架
npm install -g vsce // 发布插件

初始化一个基本框架

yo code

What type of extension do you want to create? //你想用什么类型创建,我选用的TypeScript
What's the name of your extension? // 插件的名称
What's the identifier of your extension? // 标识符
What's the description of your extension? // 描述
Initialize a git repository? // 是否初始化git
Which package manager to use? // 使用npm还是yarn管理包

创建完成后,用VS Code打开刚刚创建的文件夹。 终端进入项目根目录,安装所有依赖:

yarn install
# OR
npm install

开发插件

我们只需要关注两个文件:

  • package.json
    命令激活
 "activationEvents": [
        "onCommand:extension.throttle",
        "onCommand:extension.debounce",
        ......
    ],

命令绑定和控制面板使用

"contributes": {
        "commands": [
            {
                "command": "extension.throttle",
                "title": "method: 节流"
            },
            {
                "command": "extension.debounce",
                "title": "method: 防抖"
            },
            ......
        ]
    },
  • src/extension.ts
    注册命令
commands.registerCommand('extension.命令名称', () => {
    window.showInformationMessage('Hello World!');
});
注:命令名称对应package.json中命令激活的名称
  • 编写完测试
  1. VS Code中按下 F5 显示调试模式
  2. 在新的窗口中Win:ctrl + shift + pMac:command + shift + p
  3. 输入contributes.commands.title对应的文字确认即可

发布

  • VS Code 官方发布插件文档
  • VS Code的应用市场基于微软自己的Azure DevOps,插件的身份验证、托管和管理都是在这里。要发布到应用市场首先得有应用市场的publisher账号
  • 注册Azure DevOps账号
  • 生成token,得到token一定要复制下来保存,第二次进入不会再显示
  1. 创建发布账号:vsce create-publisher your-publisher-name
  2. 登录账号:vsce login your-publisher-name
  3. package.json中添加 "publisher":"your-publisher-name"
  4. 发布:vsce publish

安装使用

  1. 安装vscode中插件搜索框输入js-self-methods
  2. 安装完毕后按F1(Win:ctrl+shift+p、Mac:command+shift+p)
  3. 输入"method"可以查看方法列表.
  4. 或者输入关键词, 比如**"防抖"**.

参考链接

源码地址