Snippets for Fun and Profit

While I genuinely love programming, I sort of loathe repetitive lines of code that follow a pattern.

in ide , archive-worthy ,
Estimated 1 minute reading time
DRAFT ARTICLE

While I genuinely love programming, I sort of loathe repetitive lines of code that follow a pattern. This is where Code Snippets can come in handy, like reaaaaaalll handy.

If you've ever used an extension that included snippets, you'll know how powerful they can be. But what if nobody was kind enough to write an extension that fits your use case? 😱

Buckle up buttercup; it's about to get wild AF! Okay, not really, open your Command Palette and type >configure user snippets to select (or create) a snippet based on your language needs. If you want the snippets you'll be writing to be available for ANY project in VSCode; you'll want to create a new Global Snippets File. If you need the snippets for a specific project, you can create a new snippets file for 'vscode-snippets'.

I tend to develop a lot with Jekyll and NetlifyCMS, so having specific snippets for the NetlifyCMS's config is helpful for me as a global snippets file. You can see that one here.

The basic rule of thumb is that snippets are created as LANGUAGE.json and then the file is, well, it's JSON formatted.

Here's an example for perhaps javascript.json to get a quick for loop.

"JavaScript For Loop": {
  "prefix": "for",
  "body": [
    "for (i = 0; i < ${1:10}; i++) {",
    "    text += \"The number is \" + i + \"<br>\";",
    "}"
  ],
  "description": "JavaScript For Loop"
}

Don't feel like escaping a bunch of characters? Head over to this snippet generator and just paste in the code you'd like a snippet of!

Now, let's quickly break down the helpers, and what makes these so powerful. You can use $1 and so on, the number will signify where the cursor stops and provides the ability to type something. You can also give a default like ${1:10}, and the number will show as 10, but be fully highlighted so that you can type an 8, or whatever amount you'd like. You can have a complex snippet that has a ton of variables, or even reuse if you want the same string or number in multiple places.

No comments yet, add yours here.