Snippets for VS Code
This article is part of a series, this is part I. If you already know how to create a snippet have a look at the next part on how to get it published Publishing your snippet
This article is geared towardsJavaScript
andTypeScript
so the code examples will be written in mentioned languages. However the article describes snippet creation in a general way so even inJavaScript
orTypeScript
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
statementsTry-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 make sense
Logging to the screen, we tend 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.
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 aglobal
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 create 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 createhtml.json
file
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 look like this:
Worth noting is thatglobal
named 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, 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 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
andtypescript
. 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 useprefix, 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 let's 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 thelog
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 typelog
. The first item in the list our snippet. You can see thatPrint to console
is what we wrote as the snippet name andLog output to console..
is our description field. We hit thereturn
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$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:
Ok, we have a second snippet and a multiline snippet at that. Let's break it down. We supportjavascript
andtypescript
by defining that as values toscope
. Furthermore we say to activate the snippet by typingcc
. Then we come to the actual snippet ourbody
property. Now this is multiline. We can see that it is multiline as we have added x number of items in ourbody
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 theclass
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 msot 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
Now we typecc
to activate our snippet and we are faced with its name and description. Upon selecting the snippet by hitting thereturn
key we end up with this:
As you can see above we are shown the where the cursor first ends up$1
, which is right afterclass
. Hitting thetab
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 hittab
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 selectTypescript
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.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 ourprefix
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 asenum
andprivate
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 theprefix
totc
so we need to typetc
to activate our snippet. The end result looks like the following:
Above we can see our enum constructCharacterTypes
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 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 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