How YOU can boost your developer productivity with Snippets for VS Code
Tags: vscode, tutorial, javascript, showdev
Published: 2022-06-28 14:29:29

---
title: How YOU can boost your developer productivity with Snippets for VS Code
published: true
description: How YOU can boost your developer productivity with Snippets for VS Code
tags: vscode, tutorial, javascript, showdev
---
![](https://thepracticaldev.s3.amazonaws.com/i/imdlnubdjzh6e155k6jj.jpeg)

Follow me on [Twitter](https://twitter.com/chris_noring), happy to take your suggestions on topics or improvements /Chris

{% embed https://www.youtube.com/watch?v=5m9V_nx7ICY %}

> [Subscribe](https://www.youtube.com/channel/UC1Q3yUG4E0afRxccqqI3ycw?sub_confirmation=1)

> 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 `TypeScript`s o the code examples will be written in mentioned languages. However, the article describes snippet creation in a general way so even in`JavaScript`or`TypeScript`isn'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:

- [VS Code official docs](https://code.visualstudio.com/docs?wt.mc_id=devto-blog-chnoring)
Overview page of how to get started with VS Code

- [Creating your own snippets](https://code.visualstudio.com/docs/editor/userdefinedsnippets?wt.mc_id=devto-blog-chnoring)
How to create your own snippets

- [List of extensions for Azure](https://code.visualstudio.com/docs/azure/extensions?wt.mc_id=devto-blog-chnoring)
In this part we only create snippets. You can however easily create a snippet and make that into an extension. There a ton of useful extensions that can make your IDE better.

- [Free Azure Account](https://azure.microsoft.com/en-gb/free/?wt.mc_id=devto-blog-chnoring) 
If you want to try extensions for Azure or Azure Functions you will need a free Azure Account

- [Build your own extension](https://code.visualstudio.com/api/get-started/your-first-extension?wt.mc_id=devto-blog-chnoring)
At some point, you might want to build your own extension. 


##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, 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 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 a`global`snippet. Select the following from the menu : Code =&gt; Preference =&gt; User Snippets

![](https://thepracticaldev.s3.amazonaws.com/i/w9821vvw8hioekoq565z.png)

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. Select`html`for example will create`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:

![](https://thepracticaldev.s3.amazonaws.com/i/r9o0sjgjwflrzr3ytfcu.png)

Worth noting is 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 afterwards. 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:

![](https://thepracticaldev.s3.amazonaws.com/i/h0fbyloq8d82cdhg2dl3.png)

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 is`Print to console`, now 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, for now, 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, 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 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:

![](https://thepracticaldev.s3.amazonaws.com/i/kuisvc6mu6yoi02409zf.png)

We can see above that we are being presented with a list as we type`log`. The first item in the list is 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:

![](https://thepracticaldev.s3.amazonaws.com/i/l3xp04kbzbpfsbx3ps5h.png)

We see our snippet is being placed in the code window but 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:

![](https://thepracticaldev.s3.amazonaws.com/i/4uzaxenrdvqvseyvkzfu.png)

So you see where we place`$1`or`$2`matters 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:

![](https://thepracticaldev.s3.amazonaws.com/i/90sm2j2go34lxjq7g43t.png)

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 to`scope`. Furthermore, we say to activate the snippet by typing`cc`. 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`$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 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`$1`and`$2`to where they make sense to you.

#### Trying out our snippet

![](https://thepracticaldev.s3.amazonaws.com/i/q9ibp6lfwfosewac9wzz.png)

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:

![](https://thepracticaldev.s3.amazonaws.com/i/4cpvb3dkxpgevf1tuood.png)

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:

![](https://thepracticaldev.s3.amazonaws.com/i/zm9h1tk7xhtk969h01r8.png)

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 =&gt; Preferences =&gt; User Snippets. Once there we select `Typescript` and we are presented with the following result:![](/assets/language-specific.png)

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. Worth highlighting is that 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:

![](https://thepracticaldev.s3.amazonaws.com/i/9vs25uzxvk8q3fwprf3h.png)


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:

![](https://thepracticaldev.s3.amazonaws.com/i/nu4sekpeakiny58pxolf.png)

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:

```typescript
const hero = new Hero('hero', 18, CharacterTypes.Healer);
```

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](https://code.visualstudio.com/docs/editor/userdefinedsnippets?wt.mc_id=devto-blog-chnoring)

### 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