Custom Snippets in VSCode

2 min read  •  07 Jan 2022
Views:

demo-snippet


Above is the demo of one custom snippet I made for Next.js (Typescript) components. Here's how you can make custom snippet's in VSCode.


Create a code-snippets file in VSCode


snippet-file

  • Click Settings icon in bottom left.
  • Click User Snippets
  • Click New Global Snippets File or select file if you previously made one.
  • Give it a name, and done!

Once you created the code-snippets file, you can create a snippet in VSCode by adding following things in the code-snippets file-

  • Title (eg. 'Component for Nextjs')
    This is the title of your snippet.
  • Scope (eg. 'javascript, typescript')
    Your snippet will be available to you in the languages/scopes you mention here.
  • Prefix (eg. 'CompNext')
    This is the short prefix for your snippet.
  • Body (eg. ['line1', 'line2'])
    This is an array of lines of code for which you want the snippet.

You can also add $1, $2, and so on... in body to create placeholders and ask for user input there. User will be asked for input in increasing order of n ($n) and they can move to next placeholder by pressing tab.

You can also add label to these placeholders. Instead of $1 you can write ${1:label}


You can add snippets in the code-snippets file in following format-

{
  // this is a snippet
  "Title of snippet": {
    "scope": "javascript, typescript",
    "prefix": "logerr",
    "body": [
        "// line 1 of code",
        "// line 2",
        "console.error(new Error('$1'))"
    ]
  }
  // similarly add more snippets here
}

Here's how it looks-


snippet-output