vscode插件开发一(项目初始化和启动)

115 阅读1分钟

vscode插件开发一(项目初始化和启动)

环境准备

官方文档:code.visualstudio.com/api

中文资料1:vscode.js.cn/api

中文资料2:liiked.github.io/VS-Code-Ext…

Node.js ≥ 18

创建插件

  • 工具安装
npm install -g yo generator-code
  • 创建插件项目
(base) xxx@MacBook-Pro github % 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 (TypeScript)
? What's the name of your extension? HelloWorld
? What's the identifier of your extension? helloworld
? What's the description of your extension? 
? Initialize a git repository? Yes
? Which bundler to use? esbuild
? Which package manager to use? npm

项目结构如下:

-
├── .vscode
│   └── ...
├── node_modules
│   └── ...
├── src
│   ├──extension.ts
│   ├──test
│   └── extension.test.ts
├── .gitignore
├── .vscode-test.mjs
├── .vscodeignore
├── CHANGELOG.md
├── eslint.config.mjs
├── package-lock.json
├── package.json
├── README.md
├── tsconfig.json
└── vsc-extension-quickstart.md
  • package.json:项目配置,以及vscode插件配置

    • activationEvents:从 1.74+ 起,可以不手写,VSCode 会根据 contributes 自动生成

    • contributes:向 VS Code 命令面板贡献了一个可执行命令,标题为 Hello World,命令 ID 为 practice-demo.helloWorld

        "contributes": {
          "commands": [
            {
              "command": "practice-demo.helloWorld",
              "title": "Hello World"
            }
          ]
        },
        
      
  • extension.ts:插件的主要逻辑,入口文件

    模板默认提供了contributes中命令的注册

    import * as vscode from 'vscode';
    
    export function activate(context: vscode.ExtensionContext) {
    
      console.log('Congratulations, your extension "practice-demo" is now active!');
    
      const disposable = vscode.commands.registerCommand('practice-demo.helloWorld', () => {
        vscode.window.showInformationMessage('Hello World from practice-demo!');
      });
    
      context.subscriptions.push(disposable);
    }
    
    export function deactivate() {}
    

启动及测试功能

在扩展开发主机中,按 Ctrl + Shift + P / commond + shift + P 打开命令面板

输入Hello World,也就是contributes/commands[]中设置的title

执行后输出

开发人员调试窗口

  • 在扩展开发主机中,按 Ctrl + Shift + P / commond + shift + P 打开命令面板

  • 输入 Developer: Open Webview Developer Tools 并选择该命令

  • 打开基于浏览器的开发者工具

遇到的问题

vscode版本与安装的插件版本要一致

  "engines": {
    "vscode": "^1.101.0"
  },
code --version

如果出现zsh: command not found: code,需要配置环境变量,可以通过 VS Code 菜单添加命令行工具

Shell Command: Install 'code' command in PATH

Invalid problemMatcher reference: $esbuild-watch

Activating task providers npm
Error: Invalid problemMatcher reference: $esbuild-watch

搜索并安装插件:esbuild Problem Matchers