loading...
Cover image for Create your own snippets in VS Code

Create your own snippets in VS Code

gautemeekolsen profile image Gaute Meek Olsen ・1 min read

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"
  }
}

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

Posted on by:

Discussion

markdown guide
 

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

 

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/...

 

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

 

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

 

Simple but really helpful trick! Thanks Gaute