1. What is the vscode plugin?
Everyone is no stranger to vscode. It is a lightweight code editor launched by Microsoft. When using it, some plug-ins are always installed to assist us in development. These plug-ins use some APIs opened to us by vscode. The development of extended functions is carried out on the basis of, so as to solve some problems in the development and improve production efficiency. This plug-in idea on the one hand makes the code editor more lightweight; on the other hand, it can make full use of the power of the community to provide it with more diversified plug-ins. (The picture below is the rendering of a small plug-in I made)
2. What can the vscode plugin do?
What can the vscode plugin do? The core point is what open capabilities vscode provides for it. Only its open capabilities can be used by us. From the official website, the use of the vscode plugin can do the following things (this part comes from the overview of the extension capabilities of the vscode official website):
- General function
The core functions that can be used in any extension mainly include the following:
(1) Ability to add commands, configuration items, shortcut keys, menu items, and right-click menus;
(2) Store the work area or global data;
(3) Display notification information;
(4) Use quick selection to collect user input;
(5) Open the file selector to allow users to select files or folders;
(6) Use Progress API to explain long-running operations;
- Theming
Control the appearance of vscode, including the color of the source code in the editor and the color of the vscode ui, which mainly includes three types of themes:
(1) Color theme: it allows colors to be applied to text in VS Code UI components and editors;
(2) File icon theme: the location of the file icon displayed in the VS Code UI, such as file explorer, quick open list and editor tab;
(3) Product icon theme: a set of icons used in the entire UI
- Declarative language features
The declarative language feature adds basic text editing support to the programming language, such as bracket matching, automatic indentation, and syntax highlighting.
- Programming language features
The programming language function adds rich programming language support, such as hover, go to definition, diagnose errors, IntelliSense and CodeLens.
- Expansion workbench
Workbench refers to the overall Visual Studio Code UI that includes UI components such as title bar, activity bar, sidebar, control panel, editing group, and status bar. VS Code provides various APIs that allow you to add your own components to the workbench.
- debugging
You can take advantage of the debugging features of VS Code by writing a debugger extension that connects the debugging UI of VS Code to a specific debugger or runtime.
Three, vscode plug-in combat
The vscode plug-in is actually the ability that vscode provides externally. If it is not particularly needed, it is not necessary to learn the whole content completely. You only need to understand its general development ideas and problems that can be solved. The reason for saying this is because (the above is purely personal opinion, not It must be correct) Learning the content of this part requires a certain amount of energy, but it may not be able to be used in your own projects after learning. In-depth learning is not proportional to the output, so this time I will only talk about the entry-level content, the specific content Throwing requires readers to study in depth when they need this part of the ability.
3.1 Project initialization
In order to facilitate developers to develop vscode plug-ins, the official provides scaffolding corresponding to yo to generate corresponding projects.
// 安装需要的包
npm install -g yo generator-code
// 运行
yo code
The above command actually installs two packages (yo and generator-code). The purpose of these two packages is as follows:
- After the yo module is installed globally, Yeoman is installed. Yeoman is a general-purpose project scaffolding tool that can generate a corresponding project structure based on a set of templates
- The generator-code module is a VS Code extension generator. It can be used in conjunction with yo to build projects.
3.2 Important documents
After the project is generated, the directory structure is as follows. The most important files are package.json and extension.js. You can basically start to develop a vscode plug-in by understanding these two files.
#### 3.2.1 package.json
This file is a manifest file of the vscode extension. There are many fields in it. The official on each field in detail. This time we will focus on the following initialization late manifest file.
{
"name": "demo", // 插件名
"displayName": "插件", // 显示在应用市场的名字
"description": "我的第一个插件测试", // 具体描述
"version": "0.0.1", // 插件的版本号
"engines": {
"vscode": "^1.60.0" // 最低支持的vscode版本
},
"categories": [
"Other" // 扩展类别
],
// 激活事件组,在那些事件情况下被激活
"activationEvents": [
"onCommand:demo.helloWorld"
],
// 插件的主入口文件
"main": "./extension.js",
// 贡献点
"contributes": {
// 命令
"commands": [
{
"command": "demo.helloWorld",
"title": "Hello World"
}
]
},
"scripts": {
"lint": "eslint .",
"pretest": "npm run lint",
"test": "node ./test/runTest.js"
},
// 开发依赖项
"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"
}
}
In this list document, there are three main parts of focus: activationEvents, main, and contributions, which are the top priority of the entire document.
- main
It indicates where the main entrance of the plug-in is. Only when the main entrance is found, the entire project can operate normally,
- activationEvents
Specify the conditions under which the plug-in will be activated, because the plug-in can only be used normally after activation. The official website has specified the timing , so that we can set the corresponding timing as needed. (You can check it in detail when you use the specific time)
-
onLanguage
is activated when opening a file that is parsed into a specific language, such as "onLanguage:python" -
onCommand
is activated when the command is called onDebug
was activated before starting the debug session-
workspaceContains
Whenever you open a folder and the folder contains at least one file that matches the glob pattern -
onFileSystem
Whenever a file or folder from a specific scheme -
onView
Whenever expand the view of the specified id in the VS Code sidebar -
onUri
Whenever the extended system-wide Uri is opened onWebviewPanel
onCustomEditor
onAuthenticationRequest
-
*
As soon as you start vscode, the plug-in will be activated onStartupFinished
- contributes
Registering contributes by extension is used to extend various skills in Visual Studio Code. There are multiple configurations, as shown below:
-
breakpoints
breakpoint -
colors
theme color -
commands
command -
configuration
configuration -
configurationDefaults
Default language-specific editor configuration -
customEditors
custom editor debuggers
grammars
iconThemes
jsonValidation
-
keybindings
shortcut key binding languages
menus
problemMatchers
problemPatterns
productIconThemes
resourceLabelFormatters
-
snippets
specific language fragments submenus
taskDefinitions
-
themes
color theme typescriptServerPlugins
views
viewsContainers
viewsWelcome
walkthroughs
3.2.2 extension.js file
The entry file of this file is the file corresponding to the main field in package.json (not necessarily the name extension.js). Two methods will be exported in this file: activate and deactivate. The execution timing of the two methods is as follows :
- activate
This is the function executed when the plugin is activated
- deactivate
This is the method called when the plug-in is destroyed, such as releasing memory.
3.3 Actual combat
Now that you have a basic understanding of the vscode plugin, let’s start a simple actual combat to create your own vscode plugin. The functions of this plugin are as follows:
- Right-click the pop-up button in the file editing area or file name, and click the button to get the file size, creation time and modification time;
- If the obtained file is a folder, indicate that the file is a folder, not a file, and give a prompt.
3.3.1 package.json modification items
{
// ……
// 在getFileState指令下激活
"activationEvents": [
"onCommand:getFileState"
],
// 入口文件
"main": "./extension.js",
"contributes": {
// 命令
"commands": [
{
"command": "getFileState",
"title": "File State"
}
],
// 菜单项
"menus": {
// 编辑上下文菜单
"editor/context": [
{
"when": "editorFocus",
"command": "getFileState",
"group": "navigation"
}
],
// 资源管理器上下文菜单
"explorer/context": [
{
"command": "getFileState",
"group": "navigation"
}
]
}
},
// ……
}
3.3.2 Main function content
const vscode = require('vscode');
const fs = require('fs');
function activate(context) {
console.log('插件已经被激活');
// 注册命令
let commandOfGetFileState = vscode.commands.registerCommand('getFileState', uri => {
// 文件路径
const filePath = uri.path.substring(1);
fs.stat(filePath, (err, stats) => {
if (err) {
vscode.window.showErrorMessage(`获取文件时遇到错误了${err}!!!`)
}
if (stats.isDirectory()) {
vscode.window.showWarningMessage(`检测的是文件夹,不是文件,请重新选择!!!`);
}
if (stats.isFile()) {
const size = stats.size;
const createTime = stats.birthtime.toLocaleString();
const modifyTime = stats.mtime.toLocaleString();
vscode.window.showInformationMessage(`
文件大小为:${size}字节;
文件创建时间为:${createTime};
文件修改时间为:${modifyTime}
`, { modal: true });
}
});
const stats = fs.statSync(filePath);
console.log('stats', stats);
console.log('isFile', stats.isFile());
});
// 将命令放入其上下文对象中,使其生效
context.subscriptions.push(commandOfGetFileState);
}
function deactivate() {}
module.exports = {
activate,
deactivate
}
3.3.3 Effect picture
After development, the plug-in debugging effect is as follows:
3. 4 release
After the plug-in view is finished, it needs to be shared for everyone to use. There are currently three ways:
- Send the folder directly to others, let others find and put the plugin storage directory of vscode, and then restart vscode, generally not recommended;
- Package it into a vsix plug-in, and then send it to others for installation. If your plug-in involves confidentiality and is not convenient to publish to the application market, you can try this method;
- Register a developer account and publish to the official website application market. This release is the same as npm without review.
Each method is feasible, and there are many tutorials on the Internet about its release method. Today I will focus on the second method. After all, with so many plug-ins, many people are more willing to develop their own dedicated plug-ins or specific themselves. There is no need to publish the plug-ins used in the domain to the application market.
- Install the corresponding module vsce
npm i vsce -g
- Use vsce for packaging and generate the corresponding vsix file
vsce package
- Install to vscode
- After the installation is complete, it can be used normally
Four, summary
Because I have not yet encountered such a requirement in my work, this time I just gave a brief overview of the development process of the vscode plug-in without further in-depth exploration. There are such scenarios in the work that require such capabilities to solve some When there is a problem, you can quickly respond to such a solution, and it is not too late to learn further. I also hope that the friends who love to learn will also have a certain understanding of this part, make up for the lack of knowledge, and follow up for yourself Used.
V. References
vscode plugin writing actual combat
vscode plugin development strategy
1. If you think this article is good, share it, like it, and let more people see it
2. Welcome to pay attention to the front-end point, line and surface open the road to front-end salvation.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。