What is vscode plug-in?

Vscode affirmation is not strange to you, it is Microsoft jet lightweight code editor, when used to always install some plugin to help us to develop, the plug-in is to use vscode give us some open API extensions on the basis of the development, so as to solve some problems in the development, Improve production efficiency. This idea of plug-ins makes the code editor lighter on the one hand; On the other hand, it can make full use of the power of the community and provide it with more diversified plug-ins. (Below is the effect of a small plug-in I made)

What can vscode plug-in do?

What can vscode plug-ins do? The core of vscode is what open capabilities vscode provides, and only the open capabilities can be used by us. According to the official website, the following things can be done by using the VScode plug-in (this part is from the overview section of the extension capabilities of VScode official website) :

  1. Common functions

The core functions that can be used in any extension include the following:

(1) Can add commands, configuration items, shortcut keys, menu items, right menu;

(2) Store workspace or global data;

(3) Display notification information;

(4) Use quick selection to collect user input;

(5) Open the file selector for the user to select files or folders;

(6) Use the Progress API to illustrate long-running operations;

  1. themed

Controls the look and feel of vscode, including the color of the source code in the editor and the color of vscode UI. There are three main types of themes:

(1) Color theme: this allows color to be applied to text in VS Code UI components and editors;

(2) File icon theme: where file ICONS are displayed in VS Code UI, such as File Explorer, Quick Open list, and editor tabs;

(3) Product icon theme: a set of ICONS used throughout the UI

  1. Declarative language features

The declarative language feature adds basic text-editing support to programming languages, such as bracket matching, automatic indentation, and syntax highlighting.

  1. Program language features

Programming language features add rich programming language support, such as hovering, go-to definitions, diagnosing errors, IntelliSense, and CodeLens.

  1. Extension table

The workbench is the overall Visual Studio Code UI that contains UI components such as the title bar, activity bar, sidebar, control panel, edit group, status bar, and so on. VS Code provides various apis that allow you to add your own components to the workbench.

  1. debugging

You can take advantage of VS Code’s debugging capabilities by writing debugger extensions that connect VS Code’s debugging UI to a specific debugger or runtime.

Three, vscode plug-in actual combat

Vscode plug-in is actually vscode foreign provides some ability, if not particularly to learn there is no need to complete the whole content, only need to understand the general development ideas, to solve the problem, this is because (more than purely personal views, not necessarily correct) that part of the learning content requires some effort, However, it may not be used in their own projects after learning, and the input of in-depth learning is not proportional to the output. Therefore, I will only talk about the entry-level content this time, and the specific content needs to be further studied when the readers need this part of the ability.

3.1 Project initialization

In order to facilitate the development of vscode plug-in developers, the yo should provide scaffolding to generate corresponding projects.

// Install the required package
npm install -g yo generator-code
/ / run
yo code
Copy the code

The above command actually installs two packages (yo and generator-code), which are used as follows:

  1. Yeoman is a general-purpose project scaffolding tool that generates a corresponding project structure from a set of templates
  2. The generator-code module is a VS Code extension generator that can be used in conjunction with YO to build projects.

3.2 Important Documents

After the project is generated, the directory structure is shown below. The most important files are package.json and extension.js, and knowing these two files will basically get you started developing a vscode plug-in.

3.2.1 package. Json

This file is the list file of vscode extension, there are a lot of fields, each field has been described in detail, this time we focus on the following initialization post list file.

{
	"name": "demo"./ / the plugin name
	"displayName": "Plug-in".// Display the name in the app market
	"description": "My first plugin test".// Specific description
	"version": "0.0.1".// Version number of the plug-in
	"engines": {
		"vscode": "^ 1.60.0" // the lowest supported version of vscode
	},
	"categories": [
		"Other" // Extend the category].// Activate the event group, which is activated under those event conditions
	"activationEvents": [
		"onCommand:demo.helloWorld"].// The main entry file for the plug-in
	"main": "./extension.js"./ / contribution points
	"contributes": {
        / / command
		"commands": [{"command": "demo.helloWorld"."title": "Hello World"}},"scripts": {
		"lint": "eslint ."."pretest": "npm run lint"."test": "node ./test/runTest.js"
	},
    // Develop dependencies
	"devDependencies": {
		"@types/vscode": "^ 1.60.0"."@types/glob": "^ 7.1.3." "."@types/mocha": "^ 8.2.2"."@types/node": "14.x"."eslint": "^ 7.27.0"."glob": "^ 7.1.7"."mocha": "^ 8.4.0"."typescript": "^ 4.3.2." "."vscode-test": "^ 1.5.2." "}}Copy the code

In this list file, there are mainly three parts: activationEvents, Main and Contributes, which is the most important part of the whole file.

  1. main

Specifies where the main entrance of the plugin is, so that the whole project can run properly only if the main entrance is found.

  1. activationEvents

Specify under what conditions the plugin will be activated, since the plugin can only be used after activation, and the official website indicates the activation timing so that we can set the timing accordingly. (Check in detail for each time you use it)

  • OnLanguage is activated when opening a language-specific file, such as “onLanguage: Python”
  • OnCommand is activated when a command is invoked
  • onDebugActivated before starting debug talk
    • onDebugInitialConfigurations
    • onDebugResolve
  • WorkspaceContains whenever a folder is opened and contains at least one file that matches the Glob pattern
  • onFileSystemWhenever a read comes from a specificplanFile or folder
  • OnView whenever the VS Code sidebar expands the view with the specified ID
  • OnUri whenever the extended system-wide Uri is opened
  • onWebviewPanel
  • onCustomEditor
  • onAuthenticationRequest
  • * the plug-in will be activated as soon as vscode is started
  • onStartupFinished
  1. contributes

The extension registration contributes is used to extend various skills in Visual Studio Code, which has multiple configurations, as shown below:

  • Breakpoints breakpoint
  • Colors Theme colors
  • Commands command
  • The configuration configuration
  • ConfigurationDefaults Specifies the language-specific editor configuration by default
  • CustomEditors customEditors
  • debuggers
  • grammars
  • iconThemes
  • jsonValidation
  • Keybindings shortcut keybindings
  • languages
  • menus
  • problemMatchers
  • problemPatterns
  • productIconThemes
  • resourceLabelFormatters
  • Snippets language-specific snippets
  • submenus
  • taskDefinitions
  • Themes color theme
  • typescriptServerPlugins
  • views
  • viewsContainers
  • viewsWelcome
  • walkthroughs

3.2.2 the extension. Js file

This file is the entry file corresponding to the main field of package.json (not necessarily called extense.js). Two methods will be exported from this file: activate and deactivate. The execution time of the two methods is as follows:

  1. activate

This is the function executed when the plug-in is activated

  1. deactivate

This is the method that is called when the plug-in is destroyed, such as freeing memory.

3.3 the actual combat

The above has a basic understanding of VScode plug-in, the following is a simple combat, to create their own a VScode plug-in, the functions of this plug-in are as follows:

  1. By right-clicking the pop-up button in the file editing area or file name, click the button to obtain the file size, creation time and modification time;
  2. If a folder is obtained, indicate that the file is a folder, not a file, and give a hint.

3.3.1 Package. json Modified item

{
	/ /...
    // Activate under getFileState
	"activationEvents": [
		"onCommand:getFileState"].// Import file
	"main": "./extension.js"."contributes": {
        / / command
		"commands": [{"command": "getFileState"."title": "File State"}]./ / the menu item
		"menus": {
            // Edit the context menu
			"editor/context": [{"when": "editorFocus"."command": "getFileState"."group": "navigation"}].// Resource Manager context menu
			"explorer/context": [{"command": "getFileState"."group": "navigation"}}},/ /...
}
Copy the code

3.3.2 Main function content

const vscode = require('vscode');
const fs = require('fs');

function activate(context) {
	console.log('Plugin is activated');

	// Register the command
	let commandOfGetFileState = vscode.commands.registerCommand('getFileState'.uri= > {
		// File path
		const filePath = uri.path.substring(1);
		fs.stat(filePath, (err, stats) = > {
			if (err) {
				vscode.window.showErrorMessage('There was an error getting the file${err}!!!!!!!!! `)}if (stats.isDirectory()) {
				vscode.window.showWarningMessage('Detected is a folder, not a file, please select again!! `);
			}

			if (stats.isFile()) {
				const size = stats.size;
				const createTime = stats.birthtime.toLocaleString();
				const modifyTime = stats.mtime.toLocaleString();

				vscode.window.showInformationMessage('File size:${size}Bytes; The file creation time is:${createTime}; File modification time:${modifyTime}
				`, { modal: true}); }});const stats = fs.statSync(filePath);
		console.log('stats', stats);
		console.log('isFile', stats.isFile());
	});

	// Put the command into its context object for it to take effect
	context.subscriptions.push(commandOfGetFileState);
}

function deactivate() {}

module.exports = {
	activate,
	deactivate
}
Copy the code

3.3.3 rendering

After development, the debugging effect of the plug-in is as follows:

3. 4

After the plug-in views are finished, it is necessary to share them for everyone to use. There are three ways at present:

  1. Send the folder directly to others, ask them to find the directory where vscode plug-ins are stored and put them in, and then restart vscode, generally not recommended;

  2. Package it as a Vsix plugin and send it to someone else to install. If your plugin is too confidential to release to the app market, try this approach.

  3. Sign up for a developer account and post to the official app market, which is not subject to approval as NPM.

Each method is feasible, and there are many tutorials on the Internet about how to publish. Today, I will focus on the second one. After all, with so many plug-ins, many people prefer to develop their own special plug-ins or plug-ins for specific use in their own fields, and there is no need to release them to the app market.

  1. Install the corresponding vsCE module
npm i vsce -g
Copy the code
  1. Vsce is used to package and generate corresponding VSIX files
vsce package
Copy the code

  1. Installed to the vscode

  1. After the installation is completed, it can be used normally

Four,

Because the work is not yet meet this need, this time I just vscode plugin development process for a simple overview, and no further exploration, to work in such a scenario requires the ability to solve certain problems, the ability to quickly response have such solution, further study is also not too late, Also hope that love learning partners can also have a certain understanding of this part, make up for their knowledge of a lack of a link, the follow-up for their own use.

5. References

Vscode plug-in writing practice

Vscode plug-in development overview

The official documentation

1. If you think this article is good, share and like it so that more people can see it

2. Welcome to pay attention to the front end line and surface of the public account, and open the front salvation road.