DEV Community

Randy
Randy

Posted on

A tool for managing VS Code code snippets

When you realized you have typed some codes 100 times, you should save it as a code snippet. For example, I made a snippet for hapi route, when I type hapi:route it will trigger intellisense and then generate the router boilerplate code for me.

https://dev-to-uploads.s3.amazonaws.com/i/u1zwukev53co6g3pnlma.gif

It hard to write and maintain the VS Code code snippet because the code snippet was in a JSON file. So I wrote a tool to generate this JSON file for me, and I need only write the snippets in a folder.

The tool

The tool called snp (which means snippet). You can install it by curl:

$ curl -sf https://gobinaries.com/djyde/snp | sh
Enter fullscreen mode Exit fullscreen mode

It is written in Go so it can run on many platforms, include Windows.

Create your snippets

You can create a folder to organize all your code snippets now:

$ mkdir snippets
$ cd snippets
Enter fullscreen mode Exit fullscreen mode

Then you can create a file with .snp extension. The file name would become the trigger text.

For example, I want to write a hapi route snippet, now I
create a hapi:route.snp file:

$ touch hapi:route.snp
Enter fullscreen mode Exit fullscreen mode
// hapi:route.snp
---
scope: typescript,javascript
description: hapi route
---

server.route({
  path: '$1',
  method: '${2|GET,POST,PUT,DELETE|}',
  async handler(req, h) {
    $0
  }
})
Enter fullscreen mode Exit fullscreen mode

As you can see, .snp file is just a file that contains a front matter and the code snippet.

If you are not familiar about the VS Code code snippet syntax, please see https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax

Run snp -u, now go to VS Code and type hapi:route, you will see the magic:

hapi:route snippet

Conclusion

You can now use snp to manage your VS Code NATIVE code snippets, instead of using some code snippet manager apps that only help you copy and paste.

See more on https://github.com/djyde/snp

my personal snippets: https://github.com/djyde/snippets

Top comments (3)

Collapse
 
robole profile image
Rob OLeary

Nice job!

If you want to see all your snippets in one place within VS Code, you check out the extension Snippets Ranger.

logo

Collapse
 
pedrojimenez73 profile image
PedroJimenez73

Awesome, thanks so much!!

Collapse
 
dimitrigilbert profile image
Dimitri Gilbert • Edited

Well, merry Christmas to you too, unfortunately I do not come bearing gifts. :)