DEV Community

Cover image for Create your own snippets in VS Code
Gaute Meek Olsen
Gaute Meek Olsen

Posted on • Edited on • Originally published at gaute.dev

Create your own snippets in VS Code

Often you find yourself typing repetitive code or code you don't always remember by heart. With Visual Studio Code you can easily create your own code snippets so you can use them at any time. Like this:

media query snippet

Start by opening the Command Palette Ctrl + Shift + P and enter Preferences: Configure User Snippets. It will then ask you which files it should be used for, which can be CSS for example.

In the .json file, you can add as many snippets as you like in the object. This is a snippet I find useful, to write media queries.

{
  "Mobile CSS": {
    "prefix": "media",
    "body": [
      "@media only screen and (max-width: 600px) {", 
      "  ",
      "}"
    ],
    "description": "media query for mobile screen"
  }
}
Enter fullscreen mode Exit fullscreen mode

The first property is just what you name your snippet. The prefix is what you type in the editor to get the snippet suggested, body contains an array of lines of code, and a description of the snippet.

That's it. Go write code rapidly and easily.
Fast typer GIF

Top comments (5)

Collapse
 
oseifrimpong profile image
Obed Osei Frimpong

This is nice but how do you store them when you are changing laptops? Copy them into a Github Repo?

Collapse
 
ofhouse profile image
Felix Haus

Visual Studio Code is currently testing a sync feature in the insider build which should be available soon in the stable release. 🙏
Otherwise syncing over a GitHub repo works also pretty well.

code.visualstudio.com/docs/editor/...

Collapse
 
gautemeekolsen profile image
Gaute Meek Olsen

Thank you, Felix! Excellent answer, I didn't know about the sync feature coming.

Collapse
 
codemouse92 profile image
Jason C. McDonald

Oooo, thanks! I've been wondering how to do this for some time now.

Collapse
 
thisdotmedia_staff profile image
This Dot Media

Simple but really helpful trick! Thanks Gaute