Before, I always felt that it was difficult to develop plug-ins and hesitated to contact them, but every time I saw or used the plug-ins developed by others, I envied them very much. This time, there happened to be a project that needed to develop vscode plug-ins, so I took this opportunity to finally start on vscode plug-ins. This article mainly contains the introduction of development and some problems encountered in the process, I hope to give you help to avoid the same as I stepped on the pit. Let’s take a look at it in detail:

Erection of scaffolding

To use the official scaffolding build project, you need to install the scaffolding first. The command is as follows:

npm install -g yo generator-code
Copy the code

Generating project

Cut to the corresponding directory and execute Yo Code. A selection will appear as shown in the following picture. Select the extension template of the corresponding type according to your own needs, and the rest can be done step by step as prompted.

Project core structure

After executing Yo Code to generate the project, take a closer look at the structure of the project. The most important files are actually package.json and extension.js. Package. json is the configuration file of the whole plug-in project, while extension.js is the entry file of the project.

pacgage.json

Here is a common configuration for package.json files:

{
  // The plug-in name must be all lowercase letters without Spaces
  "name": "vue-typescript-snippets-plugin".// The name of the plug-in displayed in the plug-in market
  "displayName": "vue-typescript-snippets-plugin".// Briefly describe the functionality of the plug-in
  "description": "Generate VUE snippets of TS code"."version": "0.0.1".// the lowest version of vscode supported by the plug-in
  "engines": {
     "vscode": "^ 1.55.0"
  },
  // By market category, Optional values include [Programming Languages, Snippets, Linters, Themes, Debuggers,Formatters, Keymaps, SCM Providers, Other, Extension Packs, Language Packs]
  "categories": [
     "Other"].// An extended array of activation events
  "activationEvents": [
     "onCommand:vue-typescript-snippets-plugin.helloWorld"].// Plug-in entry
  "main": "./dist/extension.js".// Configure the content item
  "contributes": {
      / / command
      "commands": [{"command": "vue-typescript-snippets-plugin.helloWorld"."title": "Hello World"}},"scripts": {
      "vscode:prepublish": "yarn run package"."compile": "webpack"."watch": "webpack --watch"."package": "webpack --mode production --devtool hidden-source-map"."test-compile": "tsc -p ./"."test-watch": "tsc -watch -p ./"."pretest": "yarn run test-compile && yarn run lint"."lint": "eslint src --ext ts"."test": "node ./out/test/runTest.js"
  },
  "devDependencies": {
      "@types/vscode": "^ 1.55.0"."@types/glob": "^ 7.1.3." "."@types/mocha": "^ 8.0.4"."@types/node": "^ 12.11.7"."eslint": "^ 7.19.0"."@typescript-eslint/eslint-plugin": "^ 4.14.1." "."@typescript-eslint/parser": "^ 4.14.1." "."glob": "^ 7.1.6." "."mocha": "^ 8.2.1." "."typescript": "^ 4.1.3." "."vscode-test": "^ 1.5.0." "."ts-loader": "^ 8.0.14"."webpack": "^ 5.19.0"."webpack-cli": "^ 4.4.0"}}Copy the code

This is the package.json file that we initialize, and the core ones are activationEvents and contributes

activationEvents

ActivationEvents is used to configure activationEvents. Our plug-in was not activated at the beginning. Only when the event configured in activationEvents is triggered, the plug-in will be activated.

  • OnLanguage: Activated when the specified language file is opened

    "activationEvents": [
     	"onLanguage:html"
     ]
    Copy the code
  • OnCommand: Activated when a command is invoked

    "activationEvents": [
      "onCommand:extension.sayHello"
    ]
    Copy the code
  • OnDebug: The debugging session is activated before starting

    "activationEvents": [
      "onDebug"
    ]
    Copy the code
  • WorkspaceContains: active when a workspaceContains files that match the glob pattern

    "activationEvents": [
      "workspaceContains:**/.editorconfig"
    ]
    Copy the code
  • OnFileSystem: Activated when a file or folder is opened using the protocol

    "activationEvents": [
      "onFileSystem:sftp"
    ]
    Copy the code
  • OnView: Activated when the view with the specified ID is expanded

    "activationEvents": [
      "onView:nodeDependencies"
    ]
    Copy the code
  • OnUri: The plugin’s system-level URI is activated when it is opened. This URI must be enabled with the VScode or VScode-Insiders protocol.

    "activationEvents" [
      "onUri"
    ]
    Copy the code
  • OnWebviewPannel: activated when vscode needs to restore a webview that matches the viewType.

    "activationEvents": [
      "onWebviewPanel:catCoding"
    ]
    Copy the code
  • OnCustomEditor: activated when vscode needs to create a custom editor that conforms to the viewType.

    "activationEvents": [
      "onCustomEditor:catCustoms.pawDraw"
    ]
    Copy the code
  • OnStartupFinished: activated after vscode is started, similar to *, but does not slow vscode down.

    "activationEvents": [
      "onStartupFinished"
    ]
    Copy the code
  • *: vscode is activated upon startup. To ensure user experience, please use it when there are no other activation events.

    "activationEvents": [
      "*"
    ]
    Copy the code

contributes

One more core configuration is contributes, which is called Contribution Points and can be used to register various configuration items to extend vscode’s capabilities. Here is a list of configuration items currently available:

Configuration: The contents of the configuration are exposed to the user. You can modify the options you expose from user Settings and Workspace Settings.

ConfigurationDefaults: Configures editor defaults for a specific language.

Commands: Set the command title and command body, which will be shown in the command palette (⇧⌘P).

Menus: Menu items that set commands for an editor or file manager. At least include the timing of menu display and the command to select menu execution.

Keybindings: Configures shortcut keys

Languages: configures languages to introduce new languages or enhance existing language support of vscode.

Debuggers: configures vscode debuggers.

Breakpoints: Configures which languages can set breakpoints.

Grammars: Configures TextMate syntax for a language

Themes: add themes for vscode

IconThemes: configure vscode file iconThemes

ProductIconThemes: configure vscode productIconThemes

Snippets: Adds snippets for a language

JsonValidation: Configures the validator for the JSON file

Views: adds views to vscode

ViewsWelcome: Configures the welcome content of a custom view

ViewsContainers: View containers for configuring custom views

ProblemMatchers: Patterns for configuring problem locators

ProblemPatterns: Configure the name of the pattern that you can use in the problem locator (see above)

TaskDefinitions: Configures and defines an object structure that defines unique configuration tasks in the system

Colors: Configures the colors available for the editor decorator and status bar

TypescriptServerPlugins: configure vscode js and ts supported Typescript server plug-ins

ResourceLabelFormatters: Configures the resource label formatter, which specifies how to display urIs anywhere in the workbench

extension.js

Extension.js is the plug-in entry file that exports two functions: activate and activate. When the registered activation event is triggered, the code in Activate is executed. Deactivate provides an opportunity to clean up before the plug-in is closed. Since the code here will only be executed once, registerCommand needs to be used in activate to register the command. The parameters must be the same as those defined in package.json. Here is a simple example:

The code in the anonymous function as the second parameter to registerCommand is executed each time the command is fired. After we start debugging in vscode, we will see a new window pop up. In the new window, press command+shift+p to call the plug-in. Entering the Hello world defined by us will trigger the code in the anonymous function above to start our plug-in. A notification box appears in the lower right corner of vscode, indicating that our plug-in has been successfully launched, and we can then develop our desired functionality according to the requirements.

Run the debug

In the process of plug-in development, how can we see the effect of our plug-in in real time? Vscode provides us with the operation sequence as shown in the following picture. 1 will be cut to the debug operation panel, click 2 will open a new window, and 3 will appear as an operation bar, which can stop and refresh the plug-in already in operation. You can also use breakpoints directly in front of the corresponding code to start debugging, or you can print logs to the console via console.log(), but objects that are too complex will not be displayed.

Packaging releases

  • Install VSCE (Visual Studio Code Extension)

    npm i vsce -g
    Copy the code
  • Package as a VSIX file:

    vsce package
    Copy the code

    Tips: The generated Vsix file cannot be dragged directly into the installation, you can only select Install from VSIX installation from the upper right corner of the extension.

  • Publish to the app market

    Sign up: Get an Access token at dev.azure.com/vscode and use it to create a Publisher.

    Create a publisher account: vsce create-publisher (publisher name)

    Login Account: VSce login (Publisher name)

  • release

    vsce publish
    Copy the code

    Incremental release: Version number (major.minor.patch)

    vsce publish patch(minor/major)
    Copy the code

    Cancel publication:

    vsce unpublish (publisher name).(extension name)
    Copy the code
  • update

    Change the version number and re-execute VSCE publish

Problems and solutions

  1. After the generated demo runs, the command that triggers sayHello fails:

    The reason: the vscode version is lower than the minimum version required by the plug-in, which is the engines property defined in package.json.

  2. When I write snippets, the test finds that it does not take effect. After comparing with the official document, I find that there is a missing property scope. The previous tutorial is quite old and this property can be used without, but the latest document only takes effect when all four properties are required.

The resources

  1. VSCode plug-in development overview
  2. Vscode plug-in development Chinese documentation
  3. Vscode plug-in development English document