← Other topics

Quick Guide to Custom VSCode Snippets

Video Notes

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.

Create a new snippet file

To start, open the Command Palette with one of the following keyboard shortcuts...

  • Mac: cmd + shift + p
  • Windows: ctrl + 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

Snippet structure

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:

  • The snippet name is indicated as the key of a JSON object; in this example that’s 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.
  • Within the 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.

Another example

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.

Test it

To invoke snippets, simply start typing in the prefix and choose your snippet from the options that appear.

Conclusion

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
If this info helped you out, toss a coin in the tip jar?
← Other topics