How to Create Snippets for VS Code

christoffer noring
Level Up Coding
Published in
8 min readDec 30, 2018

--

This article is geared towards JavaScript and TypeScript so the code examples will be written in mentioned languages. However, the article describes snippet creation in a general way so even if JavaScript or TypeScript isn’t your choice of language, you will hopefully understand how snippet creation works.

Let’s talk about snippets generally. Snippets are pieces of code that we can use again and again in our code projects. They are usually created to speed up our development work so we can spend time-solving interesting problems instead of typing the _same old_ _boring code_.

We tend to use snippets someone else has created for us, or we create our own that fits our coding style.

So what is a good candidate to make a snippet out of:

  • Class, oftentimes we create plenty of classes in our solution
  • If, we tend to write quite a lot of if, if else, if else if, else statements
  • Try-catch, this is also a very common construct. Wouldn’t it be nice if there was a snippet that supported try, catch and finally?
  • Function, we create a ton of functions, so some kind of default function with a suitable number of parameters make sense
  • Logging to the screen, we tend to do this quite often for the purpose of debugging
  • Your choice, you might have things you do quite often that’s unique to you — such as reading to/from a file, accessing a database, etc. What snippets you exactly need, is up to you.

Snippets in VS Code

You can create two types of snippets in VS Code:

  • global, selectable for all languages
  • language specific, only possible to use for a specific language

Creating our first snippet

It’s almost dead easy to create a snippet so let’s do just that and explain concepts as we encounter them.

The first thing we need to do is to select the type of snippet we are about to create. Our choice here is global vs language specific. Let’s head to the menu and create a global snippet. Select the following from the menu Code /Preference / User Snippets

the above image shows you several things of interest:

  • Existing snippets, if you have created snippets before, you can select those and have them loaded into VS code
  • New Global Snippets file…, selecting this option creates a global file
  • Language-specific files, selecting any of these options will create a specific snippet file for that language. Select HTML, for example, will create a html.json file

As we stated earlier, let’s create a global file so select New Global Snippets file, the second option from the top. Let’s name it global, the result show looks like this:

It is worth noting that global named itself global.code-snippets. This file has placed itself in /Users/<username>/Library/Application Support/Code/User/snippets, if you want to look at it afterward. We also see that everything is commented out. There is some code of interest though starting with Example: so let’s uncomment that and have a closer look, so it looks like this:

Now we are looking at a working example. It is worth noting how everything starts with curly braces, and the reason for that is that we are simply editing a JSON file. The next point of interest is Print to console. This one is simply the name of the snippet. Print to console defines an object within curly braces so let’s break down each property that it defines:

  • scope, this is the supported languages for this snippet, supported languages here are javascript and typescript. Each supported language is separated by a comma. This means that if we are inside of .js or .ts file this snippet would be possible to use
  • prefix, this is what you need to type in the code window for the snippet to appear. In our case we need to type log
  • body, this is your snippet. The data type is an array and to support a snippet that has several rows we need to add a new entry to the array. We will go through that later
  • description, this is a field that lets us describe a little more what is going on
  • $1, $2, this is simply where the cursor ends up when you hit the tab button

Trying out our snippet

We stated the log is what we need to type to activate the snippet and we need to be inside of a file ending in .js or .ts . So let’s try it:

We can see above that we are being presented with a list as we type log. The first item in the list our snippet. You can see that “Print to console” is what we wrote as the snippet name and “Log output to console” is our description field. We hit the return key at this point and we end up with this:

We see our snippet is being placed in the code window, and we also see how our cursor ended up inside of the log() method. Why is that? That has a very simple explanation, that’s where we said the cursor should end up, we decided upon that here:

So you see where we place $1 or $2 matters and correctly placed it can really speed up the developer experience.

Second snippet — a class

Ok so know we understand what goes on and the inner anatomy of a snippet. Let’s create our own snippet from scratch now:

We have a second snippet and a multiline snippet at that. Let’s break it down.

We support javascript and typescript by defining that as values to scope.

We say to activate the snippet by typing cc.

Then we come to the actual snippet — our body property, which is multiline. We can see that it is multiline as we have added x number of items in our body array property. The value of the body is simply what we can expect from a class definition, with a constructor. We have added some interesting bits in here though $1 and $2. Those are placed after the class property and inside the constructor. This is done on purpose so the user has to type as little as possible. The first thing you typically do as a developer is to name the class and secondly is to add some initialization code to your constructor. If that isn’t the order in which you do things, feel free to move $1 and $2 to where they make sense to you.

Trying out our snippet

Now we type cc to activate our snippet and we are faced with its name and description. Upon selecting the snippet by hitting the return key we end up with this:

As you can see above, we are shown where the cursor first ends up $1, which is right after class. Hitting the tab key again we should go to the point of the second tab step, $2. So let’s see what that looks like:

We see we have given the class a name Test and we have hit tab and we ended up with our cursor inside of the constructor function.

Language-specific snippet

This time we want to create a language-specific snippet. So we go to the menu and select Code / Preferences / User Snippets. Once there we select Typescript and we are presented with the following result:

We can see that the filename is a bit different this time around. Instead of being called <something>.code-snippets it’s called typescript.json. So when the file ends with .json we are dealing with a language specific file. It is worth highlighting that a language-specific snippet will only work for that snippet, so if we are inside of a file ending in .js typing our prefix value won’t activate it. Instead, we need to be inside of .ts file for our snippet to be selectable.

Ok let’s think for a second, we have chosen Typescript as the specific language, so that’s all we are going to support. This means we are about to create snippets using language specific constructs like types and other things. Let’s recreate our class snippet but for Typescript:

Above we have created a snippet that utilizes some language-specific features from Typescript such as enum and private used within a constructor (that creates the backing fields for us ) and to top it off we have created a pretty cool theme, a fantasy environment. So if you had some game creation in mind, this snippet is ready for action :)

Trying out our snippet

Ok, so we set the prefix to tc so we need to type tc to activate our snippet. The end result looks like the following:

Above we can see our enum construct CharacterTypes is being created and also our class snippet. We can now easily create an object from this by for example typing:

const hero = new Hero(‘hero’, 18, CharacterTypes.Healer);

That’s it. Creating a language-specific snippet wasn’t all that different. The filename ending looks different and it is targeted to a specific language.

Summary

We have looked at snippets in VS Code. We have shown how we can

  • load existing snippets into our coding environment
  • create a global / language specific snippet
  • explain the different parts that make up a snippet and how to use it

It is my hope that you with this new found knowledge are able to both use existing snippets, create your own snippets, and boost your productivity.

Further reading

We’ve only scratched a bit on what is possible to do with a snippet but it should be enough to get you going. For more information on snippets please have a look at the official docs Snippet creation.

What’s next?

In the next article, we will cover how we can package our snippet into an extension and tell the world about it. Why not let the whole code community benefit from your creation. :) Stay tuned.

--

--