Creating Your First Visual Studio Code Extension

November 27, 2023
Jaydeep Sevlani
Creating Your First Visual Studio Code Extension

In the world of coding, we frequently encounter the repetitive task of executing commands like ’npm run,’ ’npm build’, ‘http-server’, etc. while working on our projects. 

This post will introduce you to the power of Visual Studio Code extensions, show you how they automate routine tasks and enhance your coding experience. We’ll guide you through creating an extension that allows you to effortlessly access these options with a simple right-click on a folder.

Creating your first Visual Studio Code Extension

Pre-requisites:

Node.js and npm installed on your computer

Basic knowledge of TypeScript/Javascript and Visual Studio Code

Step 1 - Setting up the development environment

Install Yeoman and the VS Code Extension Generator to set up the project.

> npm install -g yo generator-code

Step 2 - Generating a New Extension Project

After setting up the development environment, we can generate the vs code extension project. 

> ? What type of extension do you want to create? New Extension (TypeScript)
> ? What's the name of your extension? MyFirstExtension
> ? What's the identifier of your extension? myfirstextension
> ? What's the description of your extension? My first extension
> ? Initialize a git repository? Yes/No
> ? Bundle the source code with webpack? Yes/No
> ? Which package manager to use? Npm

> ? Do you want to open the new folder with Visual Studio Code? Open with `code`

Post selecting above inputs, VS code extension project will be generated and opened in the new VS code window.

Step 3 - Development of extension

You have created the project and are ready to start coding. In the project directory, ‘src/extension.ts’ can be found. ‘Src/extension.ts’ is the main entry point of the extension, where the core functionality can be defined.

Step 4 - Testing of extension

Press F5 and select VS Code Extension Development to launch a new Extension Development Host window.

In this window, extensions can be tested without affecting the primary VS Code installation.

Step 5: Packaging and Publishing of Extension

Install vsce, short for “Visual Studio Code Extensions.” Visual Studio Code Extensions is a tool for packaging, publishing, and managing VS Code extensions.

> npm install -g @vscode/vsce
> vsce package

This command will generate a ‘MyFirstExtension.vsix’ file, which can be installed manually in vs code or published to the marketplace.

NPM Menu Extension

Now that we have created a menu extension to automate the commands we use to run our pages, we will use this extension to add some options on the context menu. 

Upon selecting an option, a prompt will appear asking if you want to close existing terminals. By opting for “Yes,” all opened terminals will be disposed of.  Choosing “No” will leave current terminals unaffected. Afterward, a new terminal will open and execute the selected command for the respective folder.

Next, we will explore development perspectives in this extension step-by-step.

Step 1 -  Define the context menu contribution (Right click on folder)

To define the context menu items, we must add the commands and menus in the contributes object in package.json

The “commands” section defines custom commands that your extension adds to VS Code. A command is a specific action that users can trigger through the Command Palette or keybindings.

  • “command”: “test-ext.1” is the unique identifier for the command. These identifiers will be used to invoke the commands programmatically or through user interactions.
  • “title”: “NPM: Run” is the label that will be displayed to users in the Command Palette.

The “menus” section defines where and when the extension’s commands should appear in VS Code’s context menus.

  • “explorer/context” refers to the context menu that appears when you right-click on an item in the file explorer.
  • “when”: “explorerResourceIsFolder && resourceFilename =~ /-/” This is a condition that specifies when the menu item should be visible. In this case, the item is visible when the right-clicked item in the file explorer is a folder and its filename contains a hyphen (-).
  • “command”: “test-ext.1” This associates the command identifier “test-ext.1” with the menu item. When a user clicks on this menu item, it will trigger the command “test-ext.1”.
  • “group”: “YourGroup@1” This places the menu item in a group labeled “YourGroup” at position 1 within the context menu.

Step 2 - Add the handler to the menu option

After defining the contributes object, we need to create handlers for the added commands. These handlers should be written in the extension.ts file.

vscode.commands.registerCommand(’test-ext.1’, async (uri: vscode.Uri) => { … }); This line of the code registers a new VS Code command with the identifier ’test-ext.1’. When this command is invoked, the function defined within the arrow function (async (uri: vscode.Uri) => { … }) will be executed.

Step 3 - User Prompt: Close Existing Terminals Confirmation

In the handler, we have to write a code to take the input from the user.

const userInput = await vscode.window.showQuickPick([‘Yes’, ‘No’], { placeHolder: ‘Close existing terminals?’ });

  • This line displays a quick pick dialog using the showQuickPick method provided by the vscode module. Quick pick dialogs are used to present a list of options to the user for selection.

  • It shows a dialog with two options: Yes and No, and sets the placeholder text to ‘Close existing terminals?’.

If ‘Yes’ is Selected, Close All Opened Terminals. No Action for ‘No’.

Step 4: Send the command to the terminal

After User Selection, Open New Terminal and Execute ’npm run start <relative path>’ Command.

  • var terminal = vscode.window.createTerminal(‘cmd’);

This line creates a new terminal instance using the createTerminal method provided by the vscode.window object.

  • terminal.show();

This line instructs the newly created terminal to become visible. The show method is used to display the terminal to the user.

  • terminal.sendText(`npm run start ${relativePath}`, true);

This line sends a command to the terminal using the sendText method.

First argument is a command followed by the relative path of the selected folder, and The second argument, true, indicates that the text should be immediately executed as if the user had typed it and pressed Enter in the terminal.

Creating a Visual Studio Code extension is a powerful and versatile way to enhance your coding experience. Whether you want to streamline repetitive tasks, add new functionalities, or customize your editor to suit your needs, VS Code extensions offer endless possibilities. 

Now that we have covered the key steps in this post,  stay tuned for our upcoming blog post on PurgeCSS implementation through a dedicated VS Code extension! This extension will take your web development projects to the next level and help you efficiently remove unused CSS, optimize your code, and boost your website’s performance. Keep exploring and shaping your coding environment to suit your unique needs. 

References:

Your first extension