DEV Community

Chris Noring for Microsoft Azure

Posted on • Edited on

How YOU can boost your developer productivity with Snippets for VS Code

Follow me on Twitter, happy to take your suggestions on topics or improvements /Chris

Subscribe

Snippets is about code reuse and saving time, it's a waste of time typing everything from the beginning of every project. You may also have special requirements on top of a standard feature you want to use. All that can go into a snippet. This will teach you how to build your own snippet that you can reuse for many projects

This article will cover:

  • The what and why of snippets, maybe you never heard of snippets or if you have don't know what things in coding would make a good snippet, we will attempt to explain and inspire you
  • Snippet basics, we will cover how to write a snippet and how to use things like cursor position
  • Global vs language-specific snippets, you can author snippets that work for all languages as well as only for a specific language

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

Resources

The resource used for this app is mainly the official docs for VS Code and a specific page on Snippet creation. There is a lot more to learn so have a look in there:

The what and why of Snippets

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 our 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, elsestatements

  • 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 usually so some kind of default function with a suitable number of parameters makes 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, that can be reading to/from a file, accessing a database. 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 aglobalsnippet. 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 langugage. Selecthtmlfor example will createhtml.jsonfile

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

Worth noting is thatglobalnamed itselfglobal.code-snippets. This file has placed itself in/Users/<username>/Library/Application Support/Code/User/snippets, if you want to look at it afterwards. We also see that everything is commented out. There is some code of interest though starting withExample:so let's uncomment that and have a closer look, so it looks like this:

Now we are looking at a working example. Worth noting is how everything starts with curly braces, the reason for that is that we are simply editing a JSON file. Next point of interest isPrint to console, now this one is simply the name of the snippet.Print to consoledefines 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, for now, arejavascriptand typescript. Each supported language is separated by a comma. This means that if we are inside of.jsor.tsfile 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 typelog

  • 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, let's show 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 thelogis what we need to type to activate the snippet and we need to be inside of a file ending in.jsor.ts. So let's try it:

We can see above that we are being presented with a list as we typelog. The first item in the list is our snippet. You can see thatPrint 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 but we also see how our cursor ended up inside of thelog() 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$1or$2matters and rightly 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:

Ok, 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 toscope. Furthermore, we say to activate the snippet by typingcc. Then we come to the actual snippet our body property. Now, this 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$1and$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 you will do as a developer is most probably 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$1and$2to 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 have a look at what that looks like:

We see we have given the class a nameTest 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 calledtypescript.json. So when the file ends with.jsonwe are dealing with a language-specific file. Worth highlighting is that language-specific snippet will only work for that snippet so if we are inside of a file ending in.jstyping 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 CharacterTypesis 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);
Enter fullscreen mode Exit fullscreen mode

That's it. Creating a language-specific snippet wasn't 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 is able to both use existing snippets, create your own snippets and really 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 Creating your own snippets

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

Top comments (0)