We're live-coding on Twitch! Join us!

Creating Code Snippets in Visual Studio Code

Code Demo Project

If you've been using Visual Studio Code for any amount of time, you are probably already familiar with snippets. If you're not familiar with them, according to the Visual Studio Code docs, snippets are "templates that make it easier to enter repeating code patterns". That's kind of vague to me, so what does that really mean? It's actually simple. Snippets are shortcuts to write the code that you're tired of writing.

Snippets are shortcuts to write the code that you're tired of writing

For example, how often in Javascript do we write console statements, for loops, etc. How often in HTML do we write the boilerplate code for an HTML5 document? In CSS, how often do we write the same code to define a style simply changing the selector. All of these things are incredibly repetitive and take away from our productivity. So, snippets give you a shortcut (think a handful of letters) to complete a section of code.

Understand that snippets are context aware, meaning if you are working in a Javascript file, Javascript snippets show up. If you're working in HTMl, HTML snippets will show up. In this article, we are going to focus on creating snippets in Visual Studio Code for Javascript. We are going to take a look at existing snippets and then dive into how to create and customize them.

Check out Learn Visual Studio Code to learn everything you need to know about about the hottest editor in Web Development for only $10!

Existing Snippets in Visual Studio Code

Visual Studio Code has lots of snippets already built in. The simplest example comes in the form of Emmet. Emmet is a plugin baked into VS Code that provides TONS of snippets for HTML and CSS. If you haven't already yet, go find a video on YouTube and check it out. It will seriously save you SO MUCH time!

Probably the most notable example of this is the snippet to create HTML5 boilerplate code. To get this boilerplate code, all you have to do it type "!" and then tab. That's it!! That's the beauty of snippets.

Visual Studio Code also has lots of other built in snippets.

Essential Reading: Learn React from Scratch! (2019 Edition)

If you're curious to see what snippets you can find, open a Javascript file, type a letter, and see what pops up.

Note that snippets are the ones with black boxes to the left

Here's what happens when I type "for". Notice all of the lines with the black boxes to the left? Those are snippets!

Snippets 'for'

Let's Create our First Snippet

Visual Studio Code keeps its snippets in a json file associated with a given language. In this example, we will work with the "javascript.json" file, which, you guessed it, keeps our snippets for Javascript.

To find this file (on a Mac) go to your menu and click Code -> Preferences -> User Snippets.

Create code snippet

You will then be prompted to choose a language. Choose Javascript.

Choose Language

This is the file where we can add snippets. A snippet is basically just an object with different properties. Here are the ones we care about.

name - self-explanatory prefix - what we want the user to type to trigger the snippet body - the content of the snippet (single string or array of strings for multiline snippets) description - self-explanatory

Let's start with a snippet for a one-liner console.log() statement. Here's what it looks like.

"Console log": {
    "prefix": "clog",
    "body": "console.log('$1');",
    "description": "Log output to console"
}

"Console log" is the key/identifier/name for our object and the prefix and description are straight forward. Let's talk about the body. Notice that it's just a one line string, and the thing that probably jumps out at you is the "$1". This is called a tab stop.

Tabstops allow the user to tab between multiple locaitons in the snippet.

When a user activates the snippet, the cursor will automatically jump to the first tab stop. Now, save your javascript.json file, open up a test javascript file, type clog, and then tab. Your cursor should automatically jump inbetween the quotes as defined by the tab.

Testing clog snippet

Multiple Tabstops and Multiline Snippets

If there are more than one tabstops, the cursor will jump to the subsequent tabstob with every tab pressed. If you define the same tabstop multiple times, the text for each will be updated at the same time. This allows you to give a variable a name that is reused throughout the snippet. You can also define the final cursor position (where you want the user's cursor when they finish) by using $0. Here's a good example, creating a for loop through an array.

A couple things to note first...

  1. Instead of using $1 ($ and a number) we are using $ and a piece of text which acts as the placeholder text for you to replace.
  2. This is a multiline snippet. For multiline snippets, the body becomes an array with each line of the snippet becoming a string in that array.
  3. To format our code appropriately, we've added a "\t" to lines that need to be indented.
"For ": {
    "prefix": "forarr",
    "body": [
        "for (let ${index} = 0; ${index} < ${array}.length; ${index}++) {",
        "\tconst ${element} = ${array}[${index}];",
        "\t$0",
        "}"
    ],
    "description": "For Loop"
},

Copy this into your snippets file then try it out!

Forarr

Choices

Another useful feature is providing choices to the user. This means that instead of them having to type out something manually, they could choose from a list of relevant choices. Let's take a look back at our 'clog' snippet from earlier. What if we wanted to give the user the flexibility to write a console.error() or console.warning() instead of just console.log(). This is a great opportunity for choices. Here's what that would look like.

"Console Choice": {
    "prefix": "conc",
    "body": "console.${1|log,warning,error|}('$2');",
    "description": "Log output to console"
}

conc snippet

Activate Snippet from Keybinding

One of the coolest features of Visual Studio Code is the ability to customize it. One of the ways to do so is to override the default keybindings. Because of this, we could actually trigger one of our snippets from a keybinding instead of typging out the prefix to the snippet.

To edit your keybindings, go to the menu bar and click Code -> Preferences -> Keyboard Shortcuts.

Visual Studio Code keybindings

This gives you a semi interactive file to work with, but we can add overrides manually by clicking the keybindings.json link at the top of this file. Once you do, you'll get a side by side view of the default keybindings.json file and the one where you can override bindings.

Visual Studio Code keybinding manual override

Similar to how we define snippets, keybinding overrides are as simple as adding an object to the json file with three key properties.

  • Key - the key combination
  • Command - what we want to happen
  • When - when should this keybinding work (when the user is editing text? working in the built in terminal? )

To trigger a snippet, we need one additional property called args. Args is an object itself with two properties, langId and name.

  • langId - the language identifier (think JAVASCRIPT.json)
  • name - the name of the snippet we want to trigger

So here's what it look like to trigger a console log using the combination "cmd+c l", which means pressing command and 'c' keys togethers followed by the 'l' key.

{
    "key": "cmd+c l",
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus",
    "args": {
        "langId": "javascript",
        "name": "Print to console"
}

Save the keybindings.json file and try it out!

Wrap Up

From here, you've got all the basics. Choose the language that you're working with an edit its json file. Each snippet you want to add is a key value pair with the key being the name of the snippet and the value being the actual snippet itself. The snippet itself has three main properties: prefix, body, and description. TabStops give you complete control over tabbing through the snippet and replacing placeholder text with the real deal.

Take a look at the Visual Studio Code Extension Marketplace where you can find lots of predefined templates so tht you don't have to write them all yourself.

Resources

Like this article? Follow @jamesqquick on Twitter