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...
cmd + shift + pctrl + shift + p...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. my-snippets:
This will open a new file called my-snippets.code-snippets:
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:
"Print to console": {
"scope": "javascript,typescript",
"prefix": "log",
"body": [
"console.log('$1');",
"$2"
],
"description": "Log output to console"
}
Here’s a breakdown of each part:
Print to console.scope indicates what files this snippet will work in. Omit the scope if you want this snippet to work with any file type.prefix is 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.body contains the content of the snippet itself, with each line of the snippet in its own string.body you can create numbered placeholders ($1, $2, etc.) that will specify where your cursor will be located when the snippet is injected.description is optional and can be seen when selecting snippets.Applying what we learned above, let’s add a snippet for a basic JavaScript function:
"Function": {
"scope": "javascript,typescript",
"prefix": ["func", "f"],
"body": [
"function $1($2) {",
"\t$3",
"}",
]
}
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.
No subscriptions, no auto-renewals.
Just a simple one-time payment that helps support my free, to-the-point videos without sponsered ads.
Unlocking gets you access to the notes for this video plus all 200+ guides on this site.
Your support is appreciated. Thank you!