“This is the 17th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

preface

After two weeks of efforts, I successfully released my first plug-in vscode-cats yesterday. This article introduces the development process of the plug-in and also makes a record for myself.

You can search for vscode-cats in the VSCode extension.

  • App market: VS code-Cats

  • github: vscode-cats

It would be perfect to give Github a star.

When WE first started developing VS Code-Cats, it felt like the sky was really dark. First of all, the document is all in English, which still looks somewhat labored; Second, the implementation of this plug-in mode is not advocated by VSCode, so VSCode did not provide similar cases officially, but god pays off, there are many ways to search, query, Finally, I found the background plug-in (I feel that the developer of the background plug-in is probably the pioneer of the current mode), and then I found the VScode-Live2D plug-in. After studying the design ideas of the two leaders, I finally made the VScode-Cats plug-in successfully.

Environment to prepare

Before we can develop VSCode plug-ins, we need to install two dependencies

  • yeoman: npm install -g yo
  • generator-code: npm install -g generator-code

Initialize the project

Enter the directory where you want to develop your plug-in, and execute the Yo Code command to enter the following screen:

The vscode-Cats plugin uses TS development, so we choose New Extension (TypeScript) and follow the instructions in the interface until the dependencies are installed and the plugin demo project is initialized.

The initial directory structure is as follows (only important parts are displayed):

├ ─ ─ CHANGELOG. Md / / version change records ├ ─ ─ the README. Md / / plug-in documentation ├ ─ ─ the SRC │ └ ─ ─ the extension. The ts / / entry documents ├ ─ ─ package. The json / / ├ ─ ─ Tsconfig. json // Ts Config Exercises ─ testCopy the code

Introduction to core Files

There are two particularly important files for learning VSCode plug-in development: package.json extension.ts. After learning these two files, you will be able to carry out simple VSCode plug-in development.

package.json

Package. json declares configuration files for plug-ins and commands, which are used to register configuration such as commands.

Package. json has a number of field properties that you can configure, and HERE I’ll highlight a few of the most important ones.

ActivationEvents properties

Extended array of active events under which events are activated.

The onCommand command configured in Demo can be triggered by commands

"activationEvents": [
    "onCommand:demo.helloWorld"].Copy the code

“*” is used in plug-ins, and all types of events can trigger activation

"activationEvents": [
    "*"].Copy the code

About activationEvents more detailed configuration: code.visualstudio.com/api/referen…

Contributes configuration contribution point

Common commands include Command and Configuration.

command

Corresponding to the onCommand directive in the active event list, once configured here, it can be accessed by command.

The configurations in Demo are as follows:

"commands": [{"command": "demo.helloWorld"."title": "Hello World"}]Copy the code

configuration

The configuration properties are displayed in UI format in setting.json and VSCode plug-in Settings page.

The Cat Stroking plugin adds the following configuration to your cat:

configuration describe
vscode-cats.enabled True: enables plug-ins. False: disables plug-ins
vscode-cats.model Replace the meow microphones
vscode-cats.modelWidth Custom cat width
vscode-cats.modelHeight Custom cat height
vscode-cats.moveX Custom cat horizontal position
vscode-cats.moveY Custom cat vertical position
vscode-cats.opacity Set cat transparency
vscode-cats.position Set the cat’s left and right orientation

Here’s an example of two attributes:

"configuration": [{"title": "Cat Configuration"."type": "Object"."properties": {
        "vscode-cats.enabled": {
        "type": "boolean"."default": true."description": "Whether to enable the cat"
        },
        "vscode-cats.model": {
            "type": "string"."enum": [
                "tororo"."hijiki"]."default": "tororo"."description": "Pick that cat."}}}]Copy the code

Once configured, you can see the properties in setting.json and UI

extension.ts

The Extension file is the entry file to the project, which provides two important methods: Active deactive.

  • active: Function that is executed when the plug-in is activated
  • deactive: Function that is called when the plug-in is destroyed
export function activate(context: vscode.ExtensionContext) {
	// The code here is executed only once when the plug-in is activated
	console.log('Congratulations, your extension "demo" is now active! ');
	// The commands defined in package.json are defined here
	// Provide registerCommand to register the implementation code
        // commandId parameter must match package.json
	let disposable = vscode.commands.registerCommand('demo.helloWorld'.() = > {
        // When the command is triggered, the code here executes
        // A dialog box is displayed
		vscode.window.showInformationMessage('Hello World from demo! ');
	});
	context.subscriptions.push(disposable);
}
// called when the plug-in is deactivated
export function deactivate() {}
Copy the code

Vscode – cats and development

The above briefly introduced the basic knowledge that VSCode plug-in development must understand, with these knowledge as a foundation, next let’s take a look at the implementation of vscode-cats.

architecture

Let’s take a look at the vscode-Cats project structure

  • Extension. ts: Project entry
  • Filetype.ts: FileType (unmodified, old hacked version, new hacked version)
  • GetHTML. Ts: Get the workbench.html that can render cats
  • Html. ts: Implement check, replace, and restore workbench.html
  • OriginHTML: Remove the plug-in and restore the workbench.html file
  • Home.ts: The root file of the project
  • Uninstall. ts: uninstalls plug-ins
  • Utils: utility functions
  • Version. ts: plug-in version
  • Vshelp. ts: encapsulates VSCode’s own message prompt function

Implementation approach

  1. Preparatory work
    • throughfsModule getsworkbench.htmlThe path
    • Write and read file contentsgetContent, change the file contentsaveContentmethods
    • Encapsulate message prompt box functionshowInfoAnd prompt message and restartshowInfoRestartfunction
    • throughvscode.workspace.getConfigurationGet the plug-in’s configuration items
    • Will be able to achieve meowHTMLAdd code togetHTML.tsAnd integrate the configuration items intoHTML
    • The originalworkbench.htmlHTMLSave the code toorigin HTML.ts
  2. To install or activate a plug-in:
    • writeinstallMethod: ObtainconfigInformation,configInformation togetHTML, will be generatedHTMLCode intoworkbench.html
    • Check whether the plug-in is installed for the first time or of an earlier version. If yes, run the commandinstallmethods
  3. Uninstall or close a plug-in:
    • uninstallFrom:originHTMLGet the originalHTMLCode, writeworkbench.html

How to find out if the current version is new: By adding an identity to workbench.html, such as

The core code

  1. To obtainworkbench.htmlThe path
const base = path.dirname(require.main.filename);
const filePath = path.join(
    base,
    "vs"."code"."electron-browser"."workbench"."workbench.html"
);
Copy the code
  1. Read and write files
export const saveContent = function (filePath, content: string) :void {
  fs.writeFileSync(filePath, content, "utf-8");
};
export const getContent = function (filePath) :string {
  return fs.readFileSync(filePath, "utf-8");
};
Copy the code
  1. Reading plug-in configuration
let config = vscode.workspace.getConfiguration(this.configName); 
Copy the code
  1. install
publicinstall(refresh? :boolean) :void {
    let lastConfig = this.config; // The previous configuration
    let config = vscode.workspace.getConfiguration(this.configName); // Current user configuration
    // 1. If the current plug-in configuration does not change when the configuration file is changed, return
    if(! refresh &&JSON.stringify(lastConfig) === JSON.stringify(config)) {
      return;
    }
    The following operations can be performed: 1. Initial loading; 2. Configuration file change
    // 2. The plug-in is not started
    if(! lastConfig.enabled && ! config.enabled) {return;
    }
    // 3. Save the configuration
    this.config = config; // Update the configuration
    // 4. If close the plugin
    if(! config.enabled) {this.uninstall();
      vsHelp.showInfoRestart(this.extName + "Plug-in closed, please restart!");
      return;
    }
    / / 5. Hack style
    // Custom style content
    let content = getNewHtml(config, this.extName, this.version).replace(
      /\s*$/.""
    );
    // Write the plug-in's HTML to the workbench.html file
    saveContent(this.filePath, content);
    vsHelp.showInfoRestart(this.extName + "Configuration updated, please restart!");
  }
Copy the code
  1. uninstall
private uninstall(): boolean {
    try {
        let content = renewHTML();
        saveContent(this.filePath, content);
        return true;
    } catch (ex) {
        return false; }}Copy the code

packaging

The packaged implementation is relatively simple. Install the VSCE dependency package (NPM install -g vsce).

You can then package the plug-in as a VSIX file using the VSCE package.

Finally, you can install the vsix into VSCode to see if it works.

release

I won’t talk too much about the release, please refer to the official documentation for details.

Portal: Publishing Extensions

Be sure to note that registering a developer on maketPlace will require you to jump over the wall, and that sign-up page goes to Google. (Blood and tears)

Past wonderful articles

  • Cow guest latest front-end JS written test 100 questions
  • The latest front end of the interview questions summary (including analysis)
  • Grab the latest front end test five hundred data analysis JS interview hot spots
  • Happy cat stroking for VSCode and website adoptive cats
  • Native JavaScript soul Test (1), how much can you answer?
  • A thorough understanding of prototypes and prototype chains in JavaScript
  • Complete understanding of EventLoop in JavaScript
  • “2W word big chapter 38 interview questions” completely clear JS this pointing to the problem
  • Reference: Staggered Bouncing 3D Loading

After the language

Guys, if you find this article helpful, give a like to 👍 or follow ➕ to support me.

In addition, if this article has a question, or do not understand part of the article, you can reply to me in the comment section, we come to discuss, learn together, progress together!

If you feel that the comment section does not understand, you can also add my wechat (li444186976) or QQ (3315161861) for detailed communication, the name is battlefield small bag.