Snippets in VSCode provide a way to easily inject commonly used code “snippets” into your files. In this guide, I will quickly show you how to create your own custom snippets. For a more comprehensive guide to snippets check out the official docs: Snippets in Visual Studio Code.
To start, open the Command Palette with one of the following keyboard shortcuts...
...and start typing
snippets to find and choose the option to Configure User Snippets:
Next choose New Global Snippets file...
...and give it a name, e.g.
This will open a new file called
Global snippet files can contain snippets for different language/file types. You can also create snippet files scoped to a particular language or project. Learn more here: Snippet Scope
Within your new snippet file, an example is provided to show you the structure of a snippet:
Here’s a breakdown of each part:
- The snippet name is indicated as the key of a JSON object; in this example that’s
Print to console.
scopeindicates what files this snippet will work in. Omit the
scopeif you want this snippet to work with any file type.
prefixis the keyword(s) you’ll use to trigger this snippet. Set this to an array of strings if you wish to use more than 1 prefix.
bodycontains the content of the snippet itself, with each line of the snippet in its own string.
- Within the
bodyyou can create numbered placeholders (
$2, etc.) that will specify where your cursor will be located when the snippet is injected.
descriptionis optional and can be seen when selecting snippets.
Note that the characters
\t are used to inject indentation into the snippet body.
To invoke snippets, simply start typing in the prefix and choose your snippet from the options that appear.
The goal of this guide was to quickly cover the basics of creating snippets. If you want to learn more, including the following topics, be sure to check out the official VSCode docs on Snippets.
- Creating file type or project specific snippet files
- Assigning keyboard shortcuts to snippets
- Installing a library of snippets other developers have created via extensions
- Hide snippets that come built into VSCode