Create Extensions for Visual Studio Code (VSCode)

List Of Content

ADS Area (CARBON)

ADS Area (CARBON)

 

Getting Started

Visual Studio Code (VSCode) is one of the best code editors you can get your hands-on for software development especially for working with Web Apps, its created by Microsoft Team and Released as an Open Source Editor and has a large set of Extensions that adds features most of us need either for development, optimization or even for getting a good looking theme for your source code.

Creating Extensions either for adding a support of a new language or even a nice them you would like to have shared on the marketplace, on the other hand, you can create an extension that helps you do some file management or automate a task that you deal with a lot across your projects.

For creating a plugin or an extension for any tool or program you first need to set up the project for the tool configuration and environment in order to be able to develop the extension that it basically interacts with the tool API.

For Visual Studio Code it uses Yoman scaffolding tool for generating a configured project ready for extension development.

Yoman is a configuration and scaffolding tool that allows you to generate configured projects for a specific framework or development environment.

First, we need to install Yoman and generator-code which the one that will allow Yoman to generate the config project for VSCode extension development environment.

npm install -g yo generator-code

Make sure to install tools globally since you will need to use them from anywhere on your filesystem.

Next, you need a terminal I'm using **Cmder which is a terminal emulator for windows, However, you can use CMD for setting up the project.

yo code

Yoman will prompt you with several choices of project type you want to develop for (Typescript, Javascript, Code Theme...) From the list select javascript extension project.

Also, it will give you a prompt for project-specific name and identification plus whether you need to enable javascript typings for the extension project that will be generated.

Yoman will try to do everything for you from setting and creating the project till installing all the needed modules for developing the extension after the process finish you will find a new folder created with everything needed for development.

Now, open up the newly generated project using VSCode since its going to provide us with the needed tools and debug environment for developing and testing the extension we are going to create.

Deep Look at the Project

At first, when you see the project files and folder it may seem a bit confusing of what each file and config JSON does and why it exists or how even the extension basically works and starts executing.

It is basically set up as a normal Node.js project with node_module having the prerequisites to develop the extension and test folder for running tests on the extension where the main file that gets executed once the extension starts is extension.js

When looking inside the extension.js file you will notice two main functions (activate & deactivate) for activate it is the first function that gets called and executed once your extension is triggered (Activated) as you know for activating or triggering any extension you need to access it from the Command Pallate which can be open using (Ctrl + Shift + P) or Simply from the Top View menu.

The Activate function is going to be called when the user who has the extension installed activates the extension from the Command Palette.

On the Activate function, you will find some helpful comments and you will find a console log just for testing purposes, the message will be logged when the extension is activated on the Debug Console.

The second thing is there is a line of code that registers a new command on the command palette.

let disposable = vscode.commands.registerCommand("extension.HelloWorld",
  function() {
   vscode.window.showInformationMessage("Extension is Activated!");
  }
);

We use VSCode module which is the API module that is already imported for you and we access the commands namespace then we tell it to register a Command (in the Command Platte) with the name (extension.HelloWorld) will tell it to get the name from package.json on the property with the same name on the commands array.

//You can change title to what ever you want to get displayed on the command palette
"contributes": {
  "commands": [
    {
      "command": "extension.HelloWorld",
      "title": "Clear Console logs (BETA)"
    }
  ]
}

The title is what gets displayed on the Command Pallete as your extension name.

And finally, we got a subscription for destructing the object once the extension is deactivated.

//This will remove the disposable which returned by the create command method for freeing memory
context.subscriptions.push(disposable);

Running Extension

VSCode provides us with an encapsulated Environment to run and test our extension without interfering with other extensions throughout its awesome debug mode.

So just navigate to the debug tab on VSCode and run your extension from the Start icon (little green icon on the top left corner) or simply press F5 to run the Extension on a new VSCode instance that is made only for development purposes only.

Now, you need to open up the command palette and find your extension with its title and run it, if everything is set up as expected to be should see a message gets logged on the development window of VSCode on the Console tab and an information message shows up on the Editor, Awesome from here you are sure that your extension is working fine.

Creating a Console.log Cleaner Extension

Now, let's try to create a simple extension that removes the all the console.log statements from any code editor are open and we run on it the extension from command palette.

First, create a new file name it cleaner.js for taking care of finding the removing console.log commands on any javascript code.

/* cleaner.js */
//Import VSCode API 
const vscode = require("vscode");

class Cleaner {
  clearConsoleLogs() {
    //Get current open Editor (Active)
    const editor = vscode.window.activeTextEditor;
    //Make sure that editor is not null or there is at least one editor open.
    if (!editor) {
      //If no editor is open, show error message 
      vscode.window.showErrorMessage("There is No Open Text Editor!");
      return;
    }
    //Get Active Editor Document (Document holds the data of the editor)
    const doc = editor.document;
    //Get Text of the Editor 
    const text = doc.getText();
    //Now we need to find console.log statements using a Regular Expression
    const regex = /(console.log\(\)|console.log\(.+\));/;
    //Loop through each line on the editor text and test it if its a console.log
    text.split("\n").map((codeLine, idx) => {
      if (regex.test(codeLine)) {
        console.log("Found: ", codeLine);
        //For Now just show a message of the found console.log line
        vscode.window.showInformationMessage(codeLine);
        //This isn't doing actually a remove but i shows how the deleting process works
      }
    });
  }
}

module.exports = Cleaner;

In the ClearConsoleLogs method we first, get the currently open editor where each editor is associated with a Document that holds the Editor Date (ex: Code, language...).

Afterward, we get the text and we loop through each line of the code and run Regular Expression test against it which tests if the current line is a console.log statement or not if it is then we simply show an information message of this line (we are not doing the removing process since we just need to see who things actually works behind the scenes on a VSCode Extension).

What left is to create an instance and run the clearConsoleLogs method each time the user choose the extension command from the command palette.

//Import Cleaner Class 
const Cleaner = require("./cleaner");
...
  let cleaner = new Cleaner();
  //Register the command with a callback that calls the cleaner clearConsoleLogs method.
  let disposable = vscode.commands.registerCommand(
    "extension.ClearConsoleLogs",
    function() {
      cleaner.clearConsoleLogs();
    }
  );
...

Now if you try to save and run the extension and try to open up a simple javascript file and type of code with console.logs on then run the extension through the command palette you should see the available console.log statements gets printed to you back as an information message which means that our extension is working fine.

You can finish the development of this simple example of Console.logs Cleaner to understand other functionalities that the VSCode Extensions API provides in order to be able to create more advanced and valuable extensions.

 

What's Next

It is very important to read through the Official Documentation of VSCode Extension API and see other available functions and classes that your extension can interact with and use to create useful extensions.

Share Tutorial

Made With By

Ipenywis Founder, Game/Web Developer, Love Play Games