How to make a code snippet in VS Code

Sep 30, 2019

A guide on how to make your own "Emmet" code snippets in VSCode

Today I learned that you can make your own code snippets in VS Code! Basically, you can make your own “Emmet snippet” so that you can type your keyword, hit tab, and it autofills your entire code snippet for you. Pretty neat! I've found this very helpful, and a huge timesaver, for big chunks of code I use for lots of projects, such as a CSS reset or normalize.

Since I’ve been using a CSS styling to normalize all of my CSS (kind of like a CSS reset), I thought this would be a perfect use case for a code snippet. On a Mac, navigate to “Code —> Preferences —> User Snippets”. If you want your snippet to only apply for a specific language, you can choose that. Or you can create a global snippet by choosing “New Global Snippets file”.

The part I struggled with is that snippet files are written in JSON and I have limited knowledge of JSON and its syntax. Luckily, VS Code includes some tips when you create a new snippet file.

First, you provide the descriptive title of your snippet, followed by the scope and prefix. The scope allows you to say which languages you want the snippet to apply to. Prefix is the keyword that you will type in your normal file as your “emmet” so that when you hit tab, your snippet autofills.

CSS
"Normalize CSS: {
"scope": "css,scss,less",
"prefix": "normalize",

Then, you give it the body! In here is where you put alllll of the code that you want to be autofilled when you hit tab after typing your prefix. Pay attention to the syntax with the quotes!

JSON
“body”: [
“body {,
“box-sizing: border-box;”,
“font-size: 62.5%;”,
},
“a {,
“text-decoration: none;”,
},
]

Content is all contained within quotes and individual lines are separated by commas. If you want to add a little formatting, you can add some escape characters, like \t for a tab and \n for a new line or carriage return.

If you want to add a bit longer of a description of what this snippet does, you can add it after your body [ ].

JSON
“body”: [
],
“description”: “Your text goes here”

When you’re all done, make sure you close your { }. Everything you wrote should be inside of the “Snippet title”: { }, which itself should also be inside of some { }. So for my normalize snippet:

JSON
{
“Normalize CSS”: {
“scope”:
“prefix”:
“body”: [ ]
“description”:
}
}

Ta-da! All done with our code snippet! Try it out in a corresponding scope file!

Week 5 -- JS Fundamentals Part I