Use TypeScript to expand your VS Code !, Typescriptcode

Source: Internet
Author: User

Use TypeScript to expand your VS Code !, Typescriptcode
0x00 Preface

Microsoft held the Connect (); // 2015 Conference in New York, USA a few days ago. Through this conference, we are very happy to see that Microsoft has become more open and pragmatic. Of course, many new products and new features were released, including the beta version of VS Code. Furthermore, Microsoft has made the VS Code open source on github. In addition to these exciting news, we should also note that VS Code provides support for expansion.
So this article will talk about developing VS Code with TypeScript.

The expanded app store page used in this article:

Https://marketplace.visualstudio.com/items/JiadongChen.LicenseHeader

Github page:

Https://github.com/chenjd/VSCode-StandardHeader

0x01 Hello, world

"Hello World ". So we start from a Hello World and start to build our own VScode expansion step by step.
Before developing the extension of vscode, we must first ensure that Node. js has been installed on the computer. Then, we can use the Yeoman-based template builder provided by Microsoft to generate the vscode extended template.

npm install -g yo generator-code

Then, we only need to run the yo code command on the terminal to go to the guiding process of creating the extended template.

yo code

When TypeScript is selected as the development language during the boot process and some basic information is filled out, the first vscode extension is created.
So what has the yo code Command done for us?

The following is a complete directory of our expansion project:

. ──. Gitignore // The configuration does not need to be added to the version management File ──. vscode // VS Code integration │ ── launch. json │ ── settings. json │ ── tasks. json ──. vscodeignore // The configuration does not need to be added to the final file ├ ── README. md ├ ── src // source file │ ── extension. ts // if we use js for development and expansion, the suffix of this file is. js ├ ── test // test folder │ ── extension. test. ts // if we use js for development and expansion, the suffix of this file is. js │ ── index. ts // if we use js for development and expansion, the suffix of this file is. js ├ ── node_modules │ ├ ── vscode // vscode supports typescript language. │ ── Typescript // TypeScript compiler ├ ── out // The Output Folder after compilation (only required by TypeScript, not required by JS) │ ── src │ | ── extension. js │ | ── extension. js. map │ └ ── test │ ├ ── extension. test. js │ ── extension. test. js. map │ ── index. js │ ── index. js. map ── package. json // The extended resource configuration file ── tsconfig. json // ├ ── typings // type definition folder │ ── node. d. ts // and Node. js-associated type definition │ └ ── vscode-typings.d.ts // and VS Code-associated type definition ── vsc-extension-quickstart.md

In this case, you only need to click the Start button in the Debug area of VS Code.

In the next new VS Code in the extended development mode, you only need to input Hello World in the Command Panel to activate this template extension, A Hello World message dialog box is displayed.

So how does VS Code load and run expansion? How should we develop and expand it for ourselves or even share it with more people to better use VS Code?

0x02 about package. json

As the resource configuration file of the expansion project, package. json not only describes the extended information, but also describes the extended functions. It should be noted that when VS Code is started, the expanded package. json file will be read, and VS Code will also process the contributes content in the package. json file. This is different from extended source file extension. ts. VS Code does not load extended source Code at startup.
Next, let's take a look at the package. json file in the expansion project we just generated.

{    "name": "Standard-Header",    "displayName": "Standard-Header",    "description": "standard-header",    "version": "0.0.1",    "publisher": "JiadongChen",    "engines": {        "vscode": "^0.10.1"    },    "categories": [        "Other"    ],    "activationEvents": [        "onCommand:extension.sayHello"    ],    "main": "./out/src/extension",    "contributes": {        "commands": [{            "command": "extension.sayHello",            "title": "Hello World"        }]    },    "scripts": {        "vscode:prepublish": "node ./node_modules/vscode/bin/compile",        "compile": "node ./node_modules/vscode/bin/compile -watch -p ./"    },    "devDependencies": {        "typescript": "^1.6.2",        "vscode": "0.10.x"    }}

We can see that package. json describes some basic information about the expansion, such as the name, description, version, and publisher of the expansion. By the way of upgrading the version number, you can use the extended release tool to update the extended version that has been released to the VS Code app store.
In addition, we can even. in the json file, configure the display information of some extensions in the VS Code App Store, for example, the categories in the extended store: categories and the extended icon graph: icon and some display information on the application market homepage: galleryBanner.

..."icon": "res/icon.png","galleryBanner": {    "color": "#5c2d91",    "theme": "dark"},"categories": [    "Other"],...

Of course, the more important content is activationEvents, contributes, scripts, and main. The content of the scripts item is unique when TypeScript is used for development. It is mainly used to provide information related to ts file compilation. The main item points to the js file generated after the ts source file is compiled.

ActivationEvents

As mentioned above, by default, VS Code does not immediately execute extended Code at startup. Therefore, to enable expansion to be activated, we need to define the content of the activationEvents item in the package. json file. In the preceding example, activationEvents is defined as follows:

..."activationEvents": [    "onCommand:extension.sayHello"],...

This means that when the "onCommand: extension. sayHello" event is triggered, the extension will be activated. In VS Code, what types of activation events are there? Next, let's look at the class.

Based on the language used by the file: onLanguage :$ {language}
Expansion is activated when the opened file is in the language specified by onLanguage.
For example:

..."activationEvents": [    "onLanguage:python"]...

According to the entered command: onCommand :$ {command}
When the commands specified in onCommand are triggered, expansion is activated. In the Hello World template generated above, we can see that.

..."activationEvents": ["onCommand:extension.sayHello"]...

According to the folder: workspaceContains :$ {toplevelfilename}

"activationEvents": [    "workspaceContains:package.json"],

 Unlimited :*

..."activationEvents": [    "*"]...

Because there are no restrictions, this extension will be activated when VS Code is started. Therefore, it is not recommended to activate expansion without any restrictions. We recommend that you use it with caution.

Contribution

The contributes item in the package. json file also contains many types. If you want to classify data, you can divide it into the following types.

  • Configuration
  • Commands
  • Keybindings
  • Ages
  • Debuggers
  • Grammars
  • Themes
  • Snippets

However, this article only focuses on commands and keybindings.

Commands
For example, the "Hello World" text above defines the command title and the specific command corresponding to the title in the commands item. As follows:

"contributes": {    "commands": [{        "command": "extension.sayHello",        "title": "Hello World"    }]},

Once this extension is installed, We can find "Hello World" in the Command Panel of VS Code (my shortcut on Mac is Shift + cmd + p ", the input triggers extension. the sayHello command, and if the content defined in the extended activation event activationEvents above is "onCommand: extension. sayHello ", the activation event is triggered, and the extended code is activated.


Keybindings
Of course, for commands, you can define the keybindings item in package. json and bind the shortcut key to trigger the command. This operation is more convenient. For example, when we develop an extension for inserting a standard header, we use the binding shortcut key.

"contributes": {    "keybindings": [{        "command": "extension.insertHeader",        "key": "shift+cmd+1",        "when": "editorTextFocus"    }]},

If we have installed the extension that defines the ShortCut key triggering in VS Code, open the KeyBoard ShortCut cut of VS Code to see the ShortCut key defined in expansion and its corresponding commands.



0x03 VS Code Operating Principle

Through the content in the previous section, we can clearly understand the running process of the template expansion in the previous section.

VS Code first detects the content of the expanded package. json file and applies the contributes item in the package. json file to VS Code. In this way, the extension. sayHello command can be triggered Based on the content in the contributes item, the commands defined in the contributes item in the Command Panel, or the keybindings Shortcut Key defined in the contributes item.
Once extension. sayHello is triggered, VS Code creates an activation event called onCommand: extension. sayHello.
Meanwhile, all extensions that set activationEvents to onCommand: extension. sayHello in their package. json files will be activated. The./out/src/extension. js file is loaded into the JavaScript VM based on the main item in the package. json file. Next, VS Code will call the active function in the extension. js file. In the active function, we need to provide the specific implementation and execution of the function "extension. sayHello.
Now that we understand the basic knowledge of VS Code expansion, we can start to develop our own expansion. The purpose of this expansion is to add a License header to the source file.

0x04 expansion of inserting a License Header

Since we want to build our own VS Code, we naturally hope that some of the operational habits we like can be used in VS Code. Insert a header is such a simple small function.

First, let's take a look at the source file extended by the Hello World template above, that is, the basic content of the extension. ts file.

import * as vscode from 'vscode';export function activate(context: vscode.ExtensionContext) {    var disposable = vscode.commands.registerCommand('extension.sayHello', () => {    ...
     vscode.window.showInformationMessage('Hello World!');
...

});}

First, we naturally need to introduce the APIs in the vscode namespace to obtain the VS Code control capability.

Secondly, we noticed that the extended source file requires an export function called activate. When the event defined by activationEvents in the extended package. json file is triggered, VS Code calls the activate function.

Finally, we can see that we registered an API called "extension. sayHello "command, and provides its specific implementation, according to the logic in the template," extension. the logic of the sayHello command is to display a message whose content is "Hello World" in the window. You can see the specific effect at the beginning of this article.

The next step is very simple. We will first create a class called HeaderGenerator to execute the task of inserting a header.

class HeaderGenerator {    private _disposable: Disposable;    public insertHeader() {        // Get the current text editor         let editor = window.activeTextEditor;         if (!editor) {             return;         }                 // Define header content        var header = "License Header";                // Get the document        var doc = editor.document;                // Insert header        editor.edit((eb) => {            eb.insert(doc.positionAt(0), header);        });    }          dispose() {        this._disposable.dispose();    }}

Insert a header. Execute the edit Method of the editor (TextEditor class) of the current window. Use the insert method of the TextEditorEdit class to insert new content to the current document doc (TextDocument class.

Then, we only need to call the insertHeader method of the HeaderGenerator class in the activate function in the extension. ts file.

import * as vscode from 'vscode'; import {window, commands, Disposable, ExtensionContext, TextDocument} from 'vscode';export function activate(context: vscode.ExtensionContext) {    console.log('Congratulations, your extension "standard-header" is now active!');     let headerGen = new HeaderGenerator();    var disposable = vscode.commands.registerCommand('extension.insertHeader', () => {        headerGen.insertHeader();    });    context.subscriptions.push(headerGen);    context.subscriptions.push(disposable);}

Of course, to support the shortcut key "shift + cmd + 1", we also need to modify the contributes content in package. json:

"contributes": {    "keybindings": [{        "command": "extension.insertHeader",        "key": "shift+cmd+1",        "when": "editorTextFocus"    }]},

Then, let's first go to the extended development mode to see the effect. With the shortcut key shift + cmd + 1, we can see that the header is inserted in the VS Code window (the header content in has been changed to the MIT protocol ).

Now, We can insert the header extension in the source file, next let's use the App Store installed and even released to VS Code to share our labor results with everyone.

0x05 local installation or release in App Store

In order to "use" our expansion without having to enter the extended development mode every time, we must have our VS Code install this expansion.

In fact, local installation is very simple and convenient for your own expansion. VS Code obtains local extensions in the. vscode/extensions folder. The location of the. vscode/extensions folder is summarized as follows:

  • Windows % USERPROFILE % \. vscode \ extensions
  • Mac $ HOME/. vscode/extensions
  • Linux $ HOME/. vscode/extensions

We only need to copy one copy of the extension to the. vscode/extensions folder, and the VS Code can check the extension at startup.

Of course, in addition to self-developed extensions, we can also release them to the VS Code app store. Now we need to use an extended release tool, vsce.

First, install vsce:

npm install -g vsce

Then we need to register and log on to Visual Studio Team Services to obtain the Personal Access Token.

Once we obtain the Personal Access Token, we can use vsce to create a publisher account.

vsce create-publisher 

Then, log on and release:

vsce login vsce publish

After the release is successful, we can see our expansion in the VS Code app store.

In the Command Panel of VS Code, we can also use the command to install:

ext install 

Well, now we can use TypeScript to expand your VS Code. I hope you will have more exchanges ~

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.