Creating Snippets in Visual Studio Code

Visual Studio Code Snippets are definable templates that write boilerplate code for you. In addition to inserting boilerplate code, snippets have an interactive quality that allow you to push code out quickly.

The first step to creating a snippet in Visual Studio Code is to navigate to File > Preferences > User Snippets. Doing so will give you a menu similar to this:

Snippet Language Selection Menu

Select the language that you would like to add a snippet for and Code will open a file entitled [your-language].json. This file contains a JSON structure for defining our snippets.

My favorite snippet is for Mocha desc blocks, let’s build that. To define this snippet, I add the following JSON:

    "Mocha describe": {
    "prefix": "desc",
    "body": [
      "describe('$1', () => {",
      "  it('$2', () => $3)",

Let’s break down the anatomy of this snippet:

  • Mocha describe is the name of the snippet.
  • desc is the text that will show up in my intellisense for the snippet.
  • body an array of strings that will be inserted into my code when I execute the snippet.

Also, there are a few $[number] symbols in the body of the snippet. These symbols instruct the interactive aspect of the snippet. When I execute this snippet my cursor will be placed at the $1 symbol. After I enter some text there I can the TAB key and my cursor will be placed at the $2 symbol – and so on.

Once you are done editing [your-language].json, save and close the file.

In order to use my new Mocha desc snippet, I simply type desc and select my snippet from the intellisense menu:

Selecting Snippet From Intellisense

Personally, I tend to be pretty conservative with the snippets that I create. I think there is such a thing as “customization / configuration fatigue”. That being said, snippets like the one above are part of my daily development flow and I appreciate the speed they give me.

What do you think? Do you have a favorite snippet?

330 Words

2017-09-10 06:05 +0000