VS Code Snippets — a huge time saving feature
Snippets is a feature in VS Code that allows you to use shortcut phrases or key-bindings to automatically paste a “snippet” of code. This is super helpful whenever you have a block of code that is repeated frequently. You can even use variables to make this slightly dynamic and even more powerful.
In this example, I was working on a new Vue.js project, and I found myself writing a lot of boilerplate for each new component I made.
So, here is the barebones code snippet of what I wanted to start with in each component.
Now, I just need an easy way to get this snippet of code in each new file I make. Of course, I could keep a file called Template.vue
, for example, and just copy/paste from it each time. However, this is impractical if you have multiple snippets of code like this you may want to use.
So, this is where VS Code snippets comes in. Go to File (Windows)/Code (MacOS)
> Preferences
> User Snippets
. Select the language for the snippet you want to create/use it in. This will open a JSON file which is essentially a config file for snippets in this language. Here is mine, I selected “vue”.
So, it is relatively straightforward. prefix
is the keyword/phrase that you can type to trigger the snippet. VS Code will suggest the prefix in intellisense.
The body
is the actual content of the snippet. It is an array of strings, with each string representing one line. So, as you can observe I have a few blank strings, which are just blank lines. Just make sure you are indenting correctly across each line of code.
One final note is that I used a variable in my body string called $TM_FILENAME_BASE
, which is just the name of the current file without the extension. There are plenty of other variables that VS Code provides, which you can use in your body text. Check out other variables and cool config options here: https://code.visualstudio.com/docs/editor/userdefinedsnippets.
Hopefully this is helpful for you, and happy coding :)