This is the second chapter of VS Code’s official documentation, which focuses on getting started with plug-in writing by creating a Hello World plug-in

Hello World

Establish a framework

VS Code plug-in development starts with node.js and Git installed and Yeoman and VS Code Extension Generator installed to generate the plug-in framework

npm install -g yo generator-code
Copy the code

You can then create a plug-in framework by executing Yo Code

#? What type of extension do you want to create? New Extension (TypeScript)
#? What's the name of your extension? HelloWorld
### Press <Enter> to choose default for all options below ###

#? What's the identifier of your extension? helloworld
#? What's the description of your extension? LEAVE BLANK
#? Initialize a git repository? Yes
#? Bundle the source code with webpack? No
#? Which package manager to use? npm
Copy the code

The framework has basic functions. Using the project that VS Code just created, press F5 (do not open any files at this time) and a new VS Code interface will automatically open. In this interface, press Ctrl+Shift+P to wake up the Command Palette. Then type Hello Word:

We will then see Hello World from HelloWord in the lower right corner of the page. Tip:

Modify the source code

We can try to modify the code in the above framework

Locate to SRC /extension.ts:

// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

	// 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 "helloword" 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('helloword.helloWorld'.() = > {
	   // The code you place here will be executed every time your command is executed
         // Display a message box to the user
     vscode.window.showInformationMessage('Hello World from HelloWord! ');
	});

	context.subscriptions.push(disposable);
}

// this method is called when your extension is deactivated
export function deactivate() {}
Copy the code

We can vscode. Window. ShowInformationMessage (‘ Hello World from HelloWord! ‘); Modifications, instead vscode. Window. ShowInformationMessage (‘ this is the first plug-in! ‘); After saving the changes, run the Developer: Reload Window command in the debug Window:

Run the Hello World command again, and you can see that the prompt has changed:

In addition, we can change the command name by modifying the entire package.json contributes field, for example:

"contributes": {
   "commands": [{
      "command": "helloword.helloWorld",
+ "title": "Clock"}},Copy the code

If you change the Command name to Clock, you will see that the name in the Command Palette has changed when you execute the Command

Try an exercise that changes the content of the prompt, such as displaying the current time. You can also look it upvscode-apiTry out some of the new apis and see how they work. For example, I tried to run it herevscode.window.showErrorMessageInterfaces, it’s an interesting experiment

debugging

We can break the point directly in the source code, it will automatically stop when running, and we can put the mouse over the variable, see the specific value of the variable. If you have experience debugging a browser, you should have no difficulty

Hello World advanced

Let’s take a closer look at the Hello World example above

Function Realization Principle

On closer inspection, the Hello World plugin does three things:

  1. Register onCommand Activation events in package.json to wake up the plug-in when the user runs the Hello World command

    "activationEvents": [
       "onCommand:helloword.helloWorld"
    ]
    Copy the code
  2. Register contributes.com Mands (Contribution Points) in package.json for use in the Command Palette

    "contributes": {
       "commands": [{
            "command": "helloword.helloWorld"."title": "Clock"}}]Copy the code
  3. RegisterCommand (VS Code API) binds a specific function to the Hello World command in extension.ts

    let disposable = vscode.commands.registerCommand('helloword.helloWorld'.() = > {
     // The code you place here will be executed every time your command is executed
    
     // Display a message box to the user
     vscode.window.showErrorMessage(new Date().toLocaleString());
    });
    Copy the code

According to the above analysis, a plug-in is usually a combination of Contribution Points and VS Code apis. The official Extensions Capabilities Overview document can help you find the right Contribution Points and VS Code apis for your own plugin

The project structure

The Hello World plug-in is organized as follows:

.├ ─.vsCode │ ├─ launch.json// Config for launching and debugging the extension│ └ ─ ─ the tasks. The json// Config for build task that compiles TypeScript├ ─ ─ gitignore// Ignore build output and node_modules├ ─ ─ the README, md// Readable description of your extension's functionality├─ SRC │ ├─ exercises// Extension source code├ ─ ─ package. Json// Extension manifest├ ─ ─ tsconfig. Json// TypeScript configuration
Copy the code

Here we’ll focus on package.json and extension.ts, which are key to understanding the Hello World plug-in

Plug-in List (Extension Manifest)

Every VS Code plug-in must have a package.json file as its Extension Manifest. This package.json file contains common node.js scripts, devDependencies, and other fields. There are also fields specific to VS Code plug-ins such as Contributes, Publisher, activationEvents, etc. You can find all VS Code plug-in fields in the official Extension Manifest document.

For the Hello World plug-in, the package.json file looks like this:

{
  "name": "helloword"."displayName": "HelloWord"."description": ""."version": "0.0.1"."publisher": "vscode-lamengduo-samples"."engines": {
     "vscode": "^ 1.56.0"
  },
  "categories": [
     "Other"]."activationEvents": [
     "onCommand:helloword.helloWorld"]."main": "./dist/extension.js"."contributes": {
     "commands": [{
        "command": "helloword.helloWorld"."title": "Clock"}},"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.56.0"."@types/glob": "^ 7.1.3." "."@types/mocha": "^ 8.0.4"."@types/node": "14.x"."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

A few of these fields are important and are highlighted here:

  • name,publisher:VS Codethe<publisher>.<name>As the unique ID of the plug-in, such as the ID of this plug-invscode-lamengduo-samples.helloword
  • main: specifies the entry to the plug-in
  • activationEvents,contributes: the correspondingActivation Events 和 Contribution Points
  • engines.vscode: marks what is required by the current plug-inVS CodeMinimum version

Entrance to the file

Each VS Code plug-in has an entry file (specified by the main field in package.json). The VS Code specification requires that the plug-in entry file export two functions, activate and deactivate. When the Activation Event registered by the developer is triggered, the Activate function is executed. The deactivate function gives the plug-in developer a chance to clean up before the plug-in stops working. For many applications, deactivate is not required and can be deleted. However, this method is useful if you want to do something when VS Code is closed, plug-ins are not available, and plug-ins are uninstalled.

VS Code’s plug-in API makes a type declaration in the @types/vscode package. This file will provide services such as smart hints from the Package. json file (if the plug-in framework is generated by yo, @types/vscode will be installed by default.

Related articles

  • VS Code Plug-in Development Tutorial (1) Overview

  • VS Code plug-in Development Tutorial (2

  • VS Code Plug-in Development Tutorial (3

  • VS Code Plug-in Development Tutorial (4

  • VS Code plug-in development tutorial (5) Using Command

  • VS Code Plugin development Tutorial (6) Color Theme overview

  • VS Code plug-in development tutorial (7) Tree View

  • VS Code Plug-in Development Tutorial (8) Webview

  • Build a Custom Editor

  • VS Code Plug-in Development Tutorial (10

  • Language Server Extension Guide Language Server Extension Guide