VS Code - Snippets are not bash aliases. How to write great snippets that anyone can use
Tags: vscode, tooling, productivity
Published: 2021-08-24 08:44:45

Snippets save you keystrokes and offer guided code completion. Oddly, most snippet collections resemble [bash aliases](https://linuxize.com/post/how-to-create-bash-aliases/). If you look at the README of a snippet extension, at first, it appears to be a list of nonsense abbreviations. You must learn these abbreviations to make sense of what they do, before you can use them.

Below is an excerpt from the snippets extenion: [JavaScript (ES6) code snippets](https://marketplace.visualstudio.com/items?itemName=xabikos.JavaScriptSnippets).

<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6485c4x1h5mrk3k5riaq.png" alt="Excerpt of snippets from JavaScript (ES6) code snippets extension" width="724" height="603"/>

It hardly seems worth the effort to me to learn these. 🤕 

Snippets are a lot more powerful than aliases. We don't need to create them this way. There is a way to make them easier to learn and use!

Snippets are not limited to using a single word as the trigger (known as a `prefix` in VS Code). The quick suggestions offered by VS Code are produced from a fuzzy substring search on all prefixes. This means we can create longer, more descriptive prefixes and still be able to provide an abbreviation to trigger a snippet.

Let's look at an example to illustrate this. I created a snippets extension called [Humane JS Snippets](https://marketplace.visualstudio.com/items?itemName=robole.javascript-snippets) that has snippets created in this vain, let's try it out with an example.

Imagine that you have an array of numbers and you are looking for a function that will give you a subset of that array with only numbers greater than 80. You're not sure which array function you should use, so you need to find the best match. With this snippet set, you can type "ar" and you get a list of array functions as suggestions. They have descriptive prefixes and have an accompanying description of what each function does. You can cycle through them and search for a match. We can see that `filter()` is what we're after.

<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eju6jlyiij2qhlnwb2se.gif" alt="Demo of Humane JS snippets extensions using array functions" width="600" height="276" loading="lazy"/>

In future, if you know you want to use `filter()`, just type "filt" or some variation, and you will get that as the first suggestion. You can learn the shortest key combination by typing it out to see what is suggested. 🔥

Let's take a look at how you can create your own snippets in this manner.

## How to write more descriptive snippets

Let's look at another JavaScript example. Let's take another look at the aforementioned JavaScript snippets collection, [JavaScript (ES6) code snippets](https://marketplace.visualstudio.com/items?itemName=xabikos.JavaScriptSnippets). It has a few `for` loop snippets. The `forEach()` loop snippet has a prefix of `fre`. You can see the others in the list below.

<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7hc1qd1u42x1g6mvfb1r.png" alt="For loop snippets from JavaScript (ES6) code snippets extension" width="894" height="413" loading="lazy"/>

To trigger the `forEach` snippet, I need to type some of the letters of the prefix for it to be offered as a quick suggestion. If I can't remember that the prefix is `fre`, I might type "for" hoping to get a suggestion, but I won't get any. Doh!

<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pgfqbxs3kgt1f0pqjo2e.gif" width="600" height="262" loading="lazy" alt="Demo of for each loop snippet from JavaScript (ES6) code snippets extension">

I need to type "f" and there will be a suggestion, but since it at the very bottom of the suggestion list, I won't see it. By typing "fr", a suggestion is comes into view (number 5 in the list). I have to type "fre" for it to be the top suggestion.

Conculsion: I pretty much have to to learn the prefix to use it.

If I make my own set of snippets for the `for` loop variants, but I use complete words in the prefix, it should be easier to find them. Let's try it out.

<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1uqs1y7jz9dkyuywr9h.png" alt="For loop snippet descriptions that I made" width="894" height="564" loading="lazy"/>

For example, if I chose a prefix of "for each" for the `forEach` snippet, when I type "for" or "fr" or "fre" or "for e", I will be offered the snippet as a visible quick suggestion. This covers all of the bases.

<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ga9nllgivu4enpn7qqk.gif" width="600" height="262" loading="lazy"  alt="Demo of my for each loop snippet">

Writing snippets in this way makes them easier to discover. If I write all `for` loops variants using complete words such as "for of", then you can probably find them all without consulting the README to learn the prefix. They are likely to be suggested if you can't remember the exact prefix, and make a guess. Adding an accompanying description in the `description` field will also give more supplementary information for others to find what they're looking for. If you share your snippets with others with this in mind, it will be a lot easier for them to use them as-is.

```json
{
  "foreach loop": {
    "prefix": "for each",
    "body": [
      "${1:array}.forEach((${2:element}, index) => {",
      "\t$3",
      "});",
      "$0"
    ],
    "description": "The forEach() method executes a provided function once for each array element."
  },
}
```

For formatting purposes, you can make the `body` of the snippet easier to read if you create it as an array (rather than a string). You can have an array element for each line of the code snippet. When the snippet is executed, it will insert each element on a separate line also. You can include `\t` to add a tab for correct indentation on insertion also. This makes the snippet easier to read on insertion, especially when you need to fill out some fields to complete the snippet. Another advantage of doing this is, if you use the extension [Snippets Ranger](https://marketplace.visualstudio.com/items?itemName=robole.snippets-ranger) to view your snippets, the snippet body will be prettily formatted.

You can also provide multiple prefixes for the same snippet if you want to. It could prove useful if there are common synonyms for a code feature, or if you need to be very specific if you have a large collection of snippets. I haven't found a reason for providing multiple prefixes very often, but it is good to have the option.

```json
{
  "arrow function": {
    "prefix": ["arrow function", "=>"],
    "body": ["(${1:parameters}) => {", "\t${2:statement};", "}", "$0"],
    "description": "Creates an arrow function with optional parameters."
  },
}
```

One thing I noticed when making the above snippet is that suggestions are only offered for numeric and alphabetic characters, so if I type "=>", I won't get a suggestion, unless I hit <kbd>Ctrl</kbd>+<kbd>Space</kbd>.

## Recommended settings

You may have noticed in my examples that the quick suggestions for snippets appear as the top suggestions when I start typing a word. This may not be the case for you, unless you changed your settings related to snippets.

Snippets are mixed in with other suggestions, and by default they are placed towards the end of the list. To promote suggestions to the top of the list, you can set `editor.snippetSuggestions": "top"` in your `settings.json` file.

If you want tab completion of snippets, you can enable it with the setting `"editor.tabCompletion": "onlySnippets"` or `"editor.tabCompletion": "on"`.

You could turn off the suggestions for snippets altogether, and use tab completion to trigger snippets. You could just type "fre" and hit tab, and boom you get your snippets inserted. Again, you need to know your prefixes inside out to do this. So, it's only for the dedicated, who actually want to memorize prefixes.

### What about the builtin snippets?

As I spoke about in a previous article, [VS Code's secret snippets](https://www.roboleary.net/vscode/2020/09/22/vscode-easter-egg.html), VS Code has builtin snippets for many languages including JavaScript. In the builtin JavaScript set, there is a `forEach` snippet with a prefix of "foreach". So, if you install [JavaScript (ES6) code snippets](https://marketplace.visualstudio.com/items?itemName=xabikos.JavaScriptSnippets), you will have a duplicate. You can install the extension [Snippets Ranger](https://marketplace.visualstudio.com/items?itemName=robole.snippets-ranger) to make it easy to review the builtin snippets.

You can hide snippets if you wish. Run the command `Insert Snippet` and search for the snippet you are interested in. In the list there is an eye icon on the right-hand side of each row. Clicking the eye will hide it from IntelliSense. You can still execute the snippet through this command.

<img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u36qx39l0ml8v3kmj9zi.png" alt="Demo of disabling builtin snippet" width="634" height="268" loading="lazy"/>

I believe this is the only way to disable snippets. It is tedious if you want to disable a decent amount of snippets.

## Final word

If you are creating your own snippets, even if you prefer to use abbreviations to trigger snippets, you lose nothing by using complete words in snippet prefixes. You can still trigger the snippet with an abbreviation, and you will make your snippets easier to find. This is a win-win in my book.

If you have installed a snippets extension, you may want to create your own version of it with this in mind.

Want to learn more about snippets? You can check out my other article, [Visual Studio Code Snippets – the Definitive VS Code Snippet Guide for Beginners](https://www.freecodecamp.org/news/definitive-guide-to-snippets-visual-studio-code/). It's not just for beginners!

---

Enjoyed this article? Subscribe to my [RSS feed](https://www.roboleary.net/feed.xml) to get my latest articles.