DEV Community

Cover image for Getting Started with the VS Code Extension API
Nico Braun
Nico Braun

Posted on

Getting Started with the VS Code Extension API

Did you ever wanted to build your own VS Code Extension? Maybe because some extension you would like to use, is not available in VS Code or you just have a good idea.

The VS Code Extension API has many features and ways you can build extensions. This post will outline a general overview of what is possible.
I won't go too much into detail here as it's an extremely large topic. It is supposed to be the groundwork for more advanced posts on the topic.

The VS Code API

VS Code offers a rich API to do about anything you can think of with the application. It feels similar to working with the DOM and this may be because VS Code is an electron based application.

Below are some example commands to showcase the usage of the API.

// get properties
vscode.window.activeTextEditor.document.languageId;

// register event listener
vscode.workspace.onDidSaveTextDocument(() => {...});

// execute a command
 vscode.commands.executeCommand('editor.action.addCommentLine');
Enter fullscreen mode Exit fullscreen mode

Extension API's

There are several types of extension you can create. For example, you could create a language extension that adds tooltips when you hover over certain keywords. Or maybe you want to interact with some third party application and display the results in a separate tab.

API Description
Treeview add a tree view to the side menu
Virtual Document show data in a basic readonly tab
Web View Custom Tab that can render any html content
Custom Editor custom read/write editor replacement for specific file types
Task Provider identify and register tasks based on certain criteria such as file type
Source Control define Source Control Management (SCM) features
Debugger custom debugger
Mark Down extent built in markdown preview
Language add language features such as syntax highlighting and auto completion
Custom Data register language specific token to extend intellisence
Color Theme custom color theme
Icon Theme custom icon theme

Manifest

The manifest holds the metadata about your extension. It is part of the package.json file. In the manifest you specify for example to which part of VS Code your application will contribute. You can also expose any keybinding here. Even conditionals are possible using a when clause that can be combined with the context we are going to see later.

{
    "engines": {
        "vscode": "^1.44.0"
    },
    "main": "./out/extension.js",
    "activationEvents": [
        "onCommand:helloworld.helloWorld"
    ],
    "contributes": {
        "commands": [
            {
                "command": "helloworld.helloWorld",
                "title": "Hello World"
            }
        ]
    },
}
Enter fullscreen mode Exit fullscreen mode

Possible Contributions Points

  • configuration
  • configurationDefaults
  • commands
  • menus
  • keybindings
  • languages
  • debuggers
  • breakpoints
  • grammars
  • themes
  • snippets
  • jsonValidation
  • views
  • viewsContainers
  • problemMatchers
  • problemPatterns
  • taskDefinitions
  • colors
  • typescriptServerPlugins
  • resourceLabelFormatters

Context

The context is an important feature. You may be familiar with the concepts from other libraries and programming languages, such as React or Golang. It allows sharing state across the program. State values can be accessed inside the extension manifest for example.

vscode.commands.executeCommand(
    'setContext', 
    'myContextVariable',
    'some value'
)

Enter fullscreen mode Exit fullscreen mode

Commands

Commands are special type of contribution. They are the building blocks of any extension. Commands allow us to register our functionality and expose it to other parts of the application. We can also make our commands available via key binding.

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
  const command = 'myExtension.sayHello';

  const commandHandler = (name: string = 'world') => {
    console.log(`Hello ${name}!!!`);
  };

  context.subscriptions.push(vscode.commands.registerCommand(command, commandHandler));
}
Enter fullscreen mode Exit fullscreen mode

Setting up a Project

Ok, now we have a rough overview. Let's get our hands dirty by setting up a new project. We are going to use the official boilerplate. Afterwards I will show you how to package your extension and install it from local disc.

npm install -g yo generator-code vsce
Enter fullscreen mode Exit fullscreen mode
yo code

#      _-----_     ╭──────────────────────────╮
#     |       |    │   Welcome to the Visual  │
#     |--(o)--|    │   Studio Code Extension  │
#    `---------´   │        generator!        │
#     ( _´U`_ )    ╰──────────────────────────╯
#     /___A___\   /
#      |  ~  |
#    __'.___.'__
#  ´   `  |° ´ Y `

# ? What type of extension do you want to create? New Extension (TypeScript)
# ? What's the name of your extension? HelloWorld
# ? What's the identifier of your extension? helloworld
# ? What's the description of your extension?
# ? Initialize a git repository? Yes
# ? Which package manager to use? npm
#
# I'm all done. Running npm install for you to install the required dependencies.
# If this fails, try running the command yourself.

code ./helloworld

Enter fullscreen mode Exit fullscreen mode

The code for the extension sits in src/extension.ts. You can test the extension by running the debugger (press f5).
It will create a second VS Code instance that has your extension installed.
In the case of our example, you can run the command with by opening the command pallete (Ctrl+Shift+P) and typing hello world.

command palette

Packaging the Extension

You can package the extension with vcse. Run the following command.

vsce package
Enter fullscreen mode Exit fullscreen mode

You may need to update your package.json file as some required keys are missing. I had to add a publisher key to the file.

{   
    ...
    "publisher": "codingsafari",
    ...
}
Enter fullscreen mode Exit fullscreen mode

After the build, you have a file with a vsix extension in your directory. While you are normally supposed to make you extension available via Azure Cloud, you can actually install local vsix files.

Open the extension tab and click the three dots in the top right corner and select install from VSIX.

install from vsix

Discussion (0)