Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 40 ยท Customization and Productivity

User and Project Snippets

Create your own VS Code snippets: JSON format, prefix, body, tab stops, placeholders, choices, variables, transforms, global and project snippet files.

A snippet is a template that expands into larger code when you type a short word and press Tab. VS Code includes snippets for many languages, and extensions add more. The real power comes from writing your own: the boilerplate you type ten times a week becomes three keystrokes.

This lesson teaches the snippet file format, the placeholder syntax and the variables you can use. The JavaScript stand-ins implement a small expander that models placeholders, so you can see how $1, ${2:default} and $0 behave.

Creating a snippet file

Run Snippets: Configure Snippets from the Command Palette (or File > Preferences > Configure Snippets). Choose:

  • a language (for example javascript.json), so the snippets only appear in that language,
  • New Global Snippets file... (something.code-snippets), where each snippet lists its target languages with a scope property,
  • New Snippets file for 'project'..., which creates .vscode/something.code-snippets that you can commit and share with the team.

The format

JSON
{
  "Print to console": {
    "prefix": "log",
    "body": ["console.log('${1:label}:', ${2:value});", "$0"],
    "description": "Log a labelled value"
  },
  "React function component": {
    "scope": "javascriptreact,typescriptreact",
    "prefix": "rfc",
    "body": [
      "export function ${1:${TM_FILENAME_BASE}}() {",
      "  return (",
      "    <div>$0</div>",
      "  );",
      "}"
    ]
  }
}
  • The key ("Print to console") is the snippet's name.
  • prefix is what you type; it can be a string or an array of strings.
  • body is one string or an array of lines. Each array item becomes a line.
  • description appears in the completion list.
  • scope (global and project files only) is a comma-separated list of language IDs.
  • Escape characters the way JSON requires: "\\" for a backslash, "\"" for a quote, and \\$ when you want a literal dollar sign.

Type log, and the completion list shows the snippet; press Tab or Enter to insert it. If suggestions do not show up, check editor.tabCompletion and editor.snippetSuggestions.

Tab stops, placeholders and choices

Syntax Meaning
$1, $2, ... Tab stops: the cursor visits them in numeric order each time you press Tab
$0 The final cursor position
${1:default} A placeholder: tab stop with default text, which is selected so typing replaces it
${1|one,two,three|} A choice: a drop-down of values
$1 used twice Mirrored tab stops: typing in one edits both
${1:${2:inner}} Nested placeholders

A mirrored tab stop is perfect for pairs such as an opening and closing tag name or a function name used in the declaration and in a doc comment.

JSON
{
  "Class with constructor": {
    "prefix": "cls",
    "body": [
      "class ${1:Name} {",
      "  constructor(${2:args}) {",
      "    $0",
      "  }",
      "}",
      "",
      "export default ${1:Name};"
    ]
  }
}

Typing a name at the first ${1:Name} fills the same name at the end.

Variables

Snippets can use variables from the editor:

Variable Value
$TM_FILENAME index.js
$TM_FILENAME_BASE index
$TM_DIRECTORY Directory of the file
$TM_SELECTED_TEXT The current selection
$CLIPBOARD Clipboard contents
$CURRENT_YEAR, $CURRENT_MONTH, $CURRENT_DATE Date parts
$CURRENT_HOUR, $CURRENT_MINUTE Time parts
$RELATIVE_FILEPATH Path relative to the workspace
$LINE_COMMENT The language's line comment marker
$UUID A random UUID

Use a default when a variable is empty: ${TM_SELECTED_TEXT:code}.

JSON
{
  "Header comment": {
    "prefix": "hdr",
    "body": [
      "$LINE_COMMENT File: $TM_FILENAME",
      "$LINE_COMMENT Created: $CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE",
      "$0"
    ]
  }
}

Transforms

A variable or tab stop can be transformed with a regular expression: ${TM_FILENAME_BASE/(.*)/${1:/capitalize}/} capitalizes the file name. Format options include /upcase, /downcase, /capitalize, /pascalcase and /camelcase. Transforms are powerful but cryptic; use them sparingly.

Surround with a snippet

$TM_SELECTED_TEXT makes a snippet wrap selected code. Combine it with a keyboard shortcut using editor.action.insertSnippet (see keybindings): select lines, press the key, and they end up inside a try block.

Good snippet habits

  • Keep prefixes short but unique and memorable (rfc, log, tryc).
  • Put $0 where you want to continue typing.
  • Share team snippets as project snippets; keep personal ones in your user folder.
  • Do not paste secrets or real credentials into snippets.
  • Rely on Emmet-style abbreviations for HTML; they are built in and need no snippet file.

Runnable stand-ins

JS Stand-in: expand a snippet body

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: variables and mirrored tab stops

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does $0 mean in a snippet body?

    $0 marks where the cursor ends after all other tab stops.
  2. 2. How do you make a snippet that appears only in Python files?

    Language snippet files and the scope property restrict the language.
  3. 3. What happens when ${1:Name} appears twice?

    Repeated tab stop numbers are mirrored, which is ideal for repeated names.
  4. 4. Where do you save snippets that the whole team should share?

    Project snippet files live in .vscode and can be committed.

Summary

  • Snippets are JSON entries with prefix, body, optional description and scope.
  • $1, ${1:default}, ${1|a,b|} and $0 control the cursor path; same-numbered tab stops mirror.
  • Variables such as $TM_FILENAME_BASE and $CURRENT_YEAR fill context automatically.
  • Use language, global or project snippet files depending on who needs them.
  • Bind snippets to shortcuts with editor.action.insertSnippet.

Next: Custom Themes and Settings Profiles