Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write plug-ins to transform the VS Code editor

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to write plug-ins to transform the VS Code editor". In daily operation, I believe many people have doubts about how to write plug-ins to transform VS Code editors. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to write plug-ins to transform VS Code editors". Next, please follow the editor to study!

As a developer who relies on code as a "livelihood", the editor is really important whether bug writes well or not. Then you must be familiar with the name Visual Studio Code. As an old and powerful editor, its advantages are as follows:

First of all, its designer is a very famous engineer: Eric Gamma. Twenty years ago, he was one of the authors of Design patterns: the Foundation of Reusable object-oriented Software, a book whose place in the development community was seen as a beacon for object-oriented software development.

Second, for JavaScript writers, although there are many editors of different sizes, such as sublime, atom, webstorm, etc., VS Code differs from them in that it is open source than sublime, faster than atom, and lighter than webstorm.

I. introduction

VS Code full name Visual Studio Code is an open source Microsoft editor, GitHub on the star 115k (110000). It is based on TypeScript, the total number of code is more than 300000, large-scale well-known open source projects.

> Project address: https://github.com/microsoft/vscode

Let's first take a brief look at its product positioning. As we can see, the project author's positioning for it is a lightweight editor, so it is required to be lightweight, responsive, suitable for multiple languages, and so on. VS Code's editing capabilities come from an open source Web editor also called monaco from Microsoft, while introducing Electron: a desktop application that uses JavaScript,HTML and CSS to build cross-platform applications.

It is precisely because of a clear positioning and direction, there will be a clearer boundary. You may be wondering, how did he support multiple languages and be lightweight? Then we have to take a look at its multi-process architecture.

VS Code has a main process entry, which is responsible for some global tasks such as window management, inter-process communication, automatic updates, etc.

Rendering process, as the name implies, is responsible for the rendering of a Web page

Plug-in hosting process, the code for each plug-in runs in a separate and isolated Node environment host process, and the plug-in cannot access UI

Debug process for debugging

Language services are an important special extension that provides editing experience for many programming languages, as well as automatic additions, error checking (diagnostics), jump to definitions, and many other language functions supported by VS Code.

The core part is its plug-in system, which brings more personalized open source customization to the expansion of the editor. As long as you can find a powerful combination of VS Code plug-ins, your editor must be an advanced and efficient helper.

Let's take a look at what capabilities VS Code has for us to expand.

Do you have an itch to build a VS Code plug-in yourself? Let's do an entry-level VS Code plug-in.

II. Environmental preparation

First, you get a Node.js and a Git.

Second, "global (- g)" installs Yeoman (the modern Web application scaffolding tool) and VS Code Extension Generator, the official tool scaffolding (the tool for generating the VS Code plug-in project).

Npm install-g yo generator-code

When you see the following message, the installation is successful:

Initializing the project structure

Now that we rely on the environment, we will use Yeoman as a tool to help us create the project structure quickly. Many people may not be familiar with this scaffolding. To put it simply, Yeoman is a general-purpose scaffolding system that allows you to create any type of application. You can use it to start a new project quickly. So not only JavaScript, but also Java,Python,C# can use it to generate projects, as long as there is a corresponding generator. So let's move on to the next step by typing yo code on the command line.

Let's analyze the meaning of these options, which are literally the same, from top to bottom:

New plug-in (Typescript)

New plug-in (JavaScript)

New theme color

New language support

New code snippet

New key-value binding

New plug-in package

New language Pack (Localization)

You can see that this tool supports the creation of many types of projects, so today we start with plug-ins (Extension), so the difference between the first and the second is that if you can use TypeScript, choose the first one, which is also the official recommended one; if you don't want to write all kinds of troublesome type definitions and type checking, choose the second JavaScript. This time we choose JavaScript to do a simple introduction, and then you will need to fill in a series of initialization information as follows:

The notes are as follows:

What type of extension do you want to create? (what type of extension is created? )

What's the name of your extension? (name of the extension? Should be all lowercase letters, no spaces)

What's the identifier of your extension? (logo for extension? )

What's the description of your extension? (what is the description of the extension? )

Initialize a git repository? (initialize the git repository? )

Which package manager to use? (because we install npm, so just choose npm, if you have yarn, you can also choose yarn)

Which package manager to use (to download various npm packages)

Create a simple VS Code plug-in

The previous preparations are almost done! Then we have to start driving the "green leather train".

Enter the newly created file directory cd test-extension, the file directory:

Perhaps you think that the file directory, you can see at a glance, it is just a few configuration information or project description, but the configuration information in it is "very important" x3, which is so important that you may be missing a configuration or configuring it incorrectly. the function won't come out. So let's spend a little time talking about the information here.

First of all, you can see the values you set in the previous step in the package.json file. The main meanings in the configuration are as follows. Here is a small note. If your VS Code is old and cannot update the latest one, you can lower the version of the following engines settings. For example, I changed it to ^ 1.52.0 to make sure it is compatible with the current VS Code editor:

{"name": "test-extension", / / name of the plug-in "displayName": "test-extension", / / name displayed in the plug-in market "description": "vscode extension sample", / / plug-in description "version": "0.0.1", / / plug-in version "engines": {/ / the minimum version that supports vscode "vscode": "^ 1.52.0"} "categories": [/ / categories of plug-ins Used to distinguish "Other"], "activationEvents": [/ / event list activated by plug-ins, there can be multiple trigger mechanisms, so it is array form "onCommand:test-extension.helloWorld"], "main": ". / extension.js", / / plug-in main entry "contributes": {/ / contribution points, configuration items used to expand plug-in functions, which will not be discussed in detail here. First use command for example "commands": [{"command": "test-extension.helloWorld", "title": "Hello World"}]}, "scripts": {"lint": "eslint.", "pretest": "npm run lint", "test": "node. / 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", "glob": "^ 7.1.6", "mocha": "^ 8.2.1" "typescript": "^ 4.1.3", "vscode-test": "^ 1.5.0"}}

After we are familiar with the configuration, let's take a look at the plug-in's entry file extsnsion.js, which contains two main functions. One is activate, which represents the processing when activating the plug-in, which is usually some initialization operations such as registration commands. The other is deactivate, which represents the processing done when the plug-in is inactive. In fact, you should have a sense of body when you listen to the name. These are the two hook functions in the life cycle of the plug-in.

/ / the vscode module is quoted so that you can use many of its functions const vscode = require ('vscode'); / * * @ param {vscode.ExtensionContext} context * / function activate (context) {console.log (' Congratulations, your extension "test-extension" is now activations'); let disposable = vscode.commands.registerCommand ('test-extension.helloWorld', function () {vscode.window.showInformationMessage (' Hello World from testhouse extension');}) Context.subscriptions.push (disposable);} function deactivate () {} module.exports = {activate, deactivate}

Let's analyze the above code. You can see that there is a command in registerComman. Does it feel like deja vu? Yes, that's the command mentioned above in package.json. Let's take a look at it together:

., / / package.json "contributes": {/ / contribution points, configuration items for extending plug-in functionality, which will not be discussed in detail here. First use command as an example of "commands": [{"command": "test-extension.helloWorld", "title": "Hello World"}]},. / / extension.jsfunction activate (context) {console.log ('Congratulations, your extension "test-extension" is now activating') Let disposable = vscode.commands.registerCommand ('test-extension.helloWorld', function () {vscode.window.showInformationMessage (' Hello World from test extension');}); context.subscriptions.push (disposable);}.

Doesn't that look intuitive? The value of command set in package.json is the value of registerCommand in extension.js. So what do these orders mean? Let's run it together:

It will open a new VS Code editor for you, and plug-ins will only be loaded into this editor. Now we use the shortcut key (MacOS) command+p and type > Hello World (case-insensitive):

Enter and you will find this prompt in an inconspicuous corner in the lower right corner:

I believe that the smart combination of you code must have suddenly realized whether it is right or not! I don't know if you have this question, but where can I see the console.log above? Don't worry, let's go back to the editor of the plug-in code and take a closer look at the following side. It will not appear until we enter the above command, because in package.json we configure the plug-in activation time is onCommand:test-extension.helloWorld:

So let's change the above code with the idea of "deliberate learning", such as changing test-extension to test:

., / / package.json "activationEvents": ["onCommand:test.helloWorld"],..., "contributes": {"commands": [{"command": "test.helloWorld", "title": "Hello World"}]},. / / extension.js...function activate (context) {console.log ('I'm here!') ; let disposable = vscode.commands.registerCommand ('test.helloWorld', function () {vscode.window.showInformationMessage (' I changed command's name!');}); context.subscriptions.push (disposable);}.

Do it again according to the trigger method mentioned above, and it is still possible! So the name here is just a namespace, and you can change it to whatever name you want to apply to a more complex plug-in system. Since it is a namespace, it is fine without this prefix.

Fifth, implement a plug-in of your own

Having introduced so much before, have you found that in fact, this system is not difficult? there are bosses paving the road in front. In fact, all we have to do is "fill in the blanks" according to the rules. Now let's achieve a small function-- add a button and his click event.

Modify our package.json as follows, because I hope the plug-in has already subscribed to the button click event when it is loaded, so here we can change the activationEvents to *, so that our plug-in can activate and register the event at the very beginning:

, "activationEvents": ["*",], "contributes": {"commands": [{"command": "test.helloWorld", "title": "Hello World"}, / / register the event clicked by the button Add a small icon {"command": "test.button", "title": "button", "icon": {"light": ". / media/light/preview.svg", "dark": ". / media/dark/preview.svg"}}] / / add the following configuration "menus": {"editor/title": [{"command": "test.button", "group": "navigation"},.

Then go back to our extension.js and add a simple message reminder:

Function activate (context) {console.log ('I'm here!') ; let disposable = vscode.commands.registerCommand ('test.helloWorld', function () {vscode.window.showInformationMessage (' I changed the name of command!');}); / / add a button to click the command operation content let button = vscode.commands.registerCommand ('test.button', function () {vscode.window.showInformationMessage (' button click');}) / / remember that this new command should also be added to subscribe to context.subscriptions.push (disposable, button);}

Take a look at the effect:

Is it easy to customize the style of VS Code? Now let's analyze what we have done above. First of all, we modified the configuration in package.json to add a menus. What is this menus? The answer is the menu. The menu item definition contains the command that should be called when selecting and the condition (when) under which the item should be displayed, so you can also add a display logic to the menu item display, for example, we stipulate that this button is not displayed until you open the javascript file:

{"contributes": {"menus": {"editor/title": [{"when": "resourceLangId = = javascript", "command": "test.button", "group": "navigation"}

The meaning of group is used to define the sorting and grouping of menu items. A diagram from the official website shows the order relationship between different group. Of course, this menu is not the one we wrote above, but editor/context, so the group between different menus is actually slightly different, but generally similar, and navigation has the highest display priority:

We can also add one of these to see:

"menus": {"editor/title": [{"command": "test.button", "group": "navigation", "when": "resourceLangId = = javascript"}], "editor/context": [{"command": "test.button", "group": "navigation", "when": "resourceLangId = = javascript"}]}

The effect is the same:

If you are curious about any other menus, here is a brief translation of the contents of the official website (only common menus are not all):

Configure the name menu location of the menu item commandPalette global command panel explorer/context explorer context menu editor/context editor right-click context menu editor/title editor title bar Display text editor/title/context editor title right context menu debug/callstack/context debug stack view context menu debug/toolbar debug toolbar scm/titleSCM title menu view/title look at the title menu touchBarmacOS touch bar timeline/title timeline view title menu bar extension/context extender view context menu, this is the end of the study on "how to write plug-ins to transform the VS Code editor" I hope I can solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report