Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

User Snippets – VS Code

Details

To open up a User Snippets file on Windows, go to File > Preferences > User Snippets. To open up a User Snippets file on macOS, go to Code > Preferences > User Snippets. These commands will open up a list of languages that you can click on to open up their snippets file. If you’d like to create a snippet for a specific language, click on that language in the list. You can also create a new global snippets file.

For example, if you click on the css option, it will open up a file called css.json. All of the User Snippets files are JSON files.

Template

To create a snippet, use the following template. Every snippet has a name, prefix, body, and description.

First, make sure you are adding your snippet in between the curly braces that are already in the file. Then, give your snippet a name, followed by a colon and curly braces.

{
  // ...
  "Snippet Name": {

  }
}

Inside the curly braces, create a prefix key followed by a colon. Then give the prefix a value.

{
  // ...
  "Snippet Name": {
    "prefix": "prefix-value",
  }
}

After the prefix, add a body key followed by a colon. Then add a pair of square brackets. Inside the square brackets, separate the values for the body with commas. Each value here will appear on its own line, so if you want everything to appear on one line then only use one value.

You can use placeholders in the body value with the following format: $1, $2, $3, and so on. When you use the snippet, you can use the Tab key to move between the placeholders. The placeholder $0 marks the last spot your cursor will go when using the Tab key.

{
  // ...
  "Snippet Name": {
    "prefix": "prefix-value",
    "body": ["part one", "$1", "part two"],
  }
}

After the body, add a description key followed by a colon. Then add a description value.

{
  // ...
  "Snippet Name": {
    "prefix": "prefix-value",
    "body": ["part one", "$1", "part two"],
    "description": "Optional description value"
  }
}

Advanced placeholders

You can also use more advanced placeholders in the body like this: ${1:default-text}. The text after the colon is the default text that will be used if you don’t change it.

Exercises

There are no exercises for this lesson.

References

Snippets – VS Code Docs

Back to: VS Code Tips Reference