loading...

Creating Custom Snippets for VS Code

dannylee8 profile image Danny Lee ・5 min read

Introduction

Six months ago I began my journey into coding. By luck or by kismet, my sister-in-law had just gone through a coding bootcamp and recommended the Flatiron School to me. I applied, was accepted, paid my fees, did my pre-work and joined my cohort (9.16.19). [Coursereport.com: The 48 best bootcamps]

It has been an incredibly challenging and frustrating uphill climb. Figuring out how to overcome obstacles to learning and breakthrough to the other side of a problem and discover the solution can be overwhelmingly difficult, not even taking into account making that solution as succinct and elegant as poetry.

“Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.
- Grady Booch

”Learning to code, whatever the language, is not an easy thing. No matter how readable, high-level or elegant a particular programming language’s syntax is, it still requires a very exact … well, for lack of a better word, syntax.

Trying to learn a new language’s full breadth of functions, classes and methods, libraries, frameworks, modules and so on, while trying to bring together (sometimes) intricate and complex logic, while trying to ensure that all your i’s are dotted and all your t’s are crossed can feel a bit like a China plate spinning act.

One way to off-load some of this mental overload is to use code snippets. There are already many pre-made snippets (in Extensions Marketplace [doc]) available on VS Code for many different languages and the generic ones can be of great use. But, what if you wanted to make your own? Its actually not hard at all, though it looks a bit daunting at first, pretty soon you’ll be able add custom code, comment headers, even ASCII art to liven up your code!


Getting Started

[Link to: Official Docs]

After opening VSC, you’ll need to navigate to the menu item Code/Preferences/User Snippets:

Then you’ll see a list of previously made snippet files (JSON format) and a list of programming languages:

I’m currently learning Javascript, so I’ll use that language as an example. I used the “javascript.json” file which will load my snippets whenever I have a file with a .js suffix in the file name.

The other option is to create a “New Global Snippets file…” which will load all the time. You can also make files specifically for Ruby, HTML, or whatever suits you.

In the case that you are like me and can’t stand to see a bunch of random test Snippet files and you want to delete them, they default to the directory:

~/Library/Application Support/Code/User/snippets

If they don’t happen to be there, then you can load up one of the “to-be-deleted” snippet files and if you use “Save as…” it will open up the directory that it is currently in.


What do Snippets look like in the raw?

After loading your snippet file (javascript.json in this case), you will see opening and closing curly (“{}”) braces that will enclose your JSON formatted snippets.

Here are a pair of sample snippets. The first is a snippet to create a CAPITALIZED set of constants for the headers of a fetch() call. The second snippet is a fetch() call with a PATCH method. Take a look at it for a minute before moving down to “original” code below.

So, it looks a bit crazy, but basically it is a key (“Fetch-headers”) with a value, which contains a few different keys:

  • prefix: These will activate (“bring up”) the snippet while you type. You can set multiple string values so that you can make aliases or just descriptive text (eg. “fetch headers”)
  • body: This is the code itself, surrounded with double quotes. We are use double quotes to surround each line of text, which are, in turn, delineated with a comma at the end of each line. There are certain characters (ie. “, $, {}, \) which need to be “escaped” so that they will be read and print properly. If we didn’t escape a double quote (“) VSC would read it as the end of the line, rather than a character to be printed.
  • description: A description to show in your list of available snippets:


The original code

When I want to put a piece of code in a snippet what I do is open up a new file, paste my code, and paste a template of the snippet. And then I add my PREFIX, and DESCRIPTION, and then I start editing my code, step by step:

Step 1: Put double quotes (“) around each line and add a comma (,) to the end of each line.

Step 2: Escape all my inner double quotes, and special characters ($, {}, \), commas and pipes (|) may also need to be escaped in certain circumstances.

Step 3: Add my tabs for clear code formatting by using “\t” (tab)

Step 4: Lastly, and most complicated is adding Tabstops. These are places in your code that you can use the TAB key to hop through and edit. You can set them in order with prepared values (ex: ${1:key}:${2:value}). You also code in choices, use System variables (date, current filename, directory, contents of clipboard, etc), or fill in other Tabstop values with Variable Transforms that allow for conditional inserts, inserts based on input after the snippet is placed and Regexp (regular expression) matching.

Okay don’t worry about Step 4 if it seems like too much. After you try building out a few snippets, you’ll see its not all that hard to get the basic functionality. Maybe you’ll even enjoy implementing the level 2 functionality of adding basic Tabstops, eg.${1:key}:${2:value}.

I feel like this is where most people’s “time spent to learn and implement” and “usefulness-to-me index” meet.


Parting words

My advice would be to open up one of your Snippet files, such as “javascript.json” if you’re learning Javascript. Then, copy and paste the code, open up or create (and save) a .js appended file and try typing “fetch get” or “feg” and see if it works. (If not, you may need to close VSC completely and restart it.) You might find it slightly addictive and have to refrain from just snippet’ing everything.

Good luck! And best wishes on your coding journey!


[first published 11/24/2019]

Posted on by:

dannylee8 profile

Danny Lee

@dannylee8

a nyc based programming enthusiast, who also loves handywork, propagating african violets, gardening, woodwork, welding, painting, and travelling to bali, to visit my future home.

Discussion

pic
Editor guide