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:

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?