Online Code to Snippet Converter Tool, Support JavaScript / TypeScript / React / JSX / TSX      

Please enter a snippet name (name)
Please enter a snippet prefix (prefix)
Please enter a snippet description (description)
Please enter the code text (code body)
Generation Type
Generated Snippet Result

VSCode How to use code snippets


Snippets in Visual Studio Code
VS Code snippets are a powerful way to boost your coding productivity by automating the insertion of commonly used code blocks. They can be simple text expansions or more complex templates with placeholders and variables. Here's how to leverage them:

Creating Snippets:

Access Snippet Settings: Go to File > Preferences > User Snippets (Code > Preferences > User Snippets on macOS). Alternatively, use the command palette (Ctrl+Shift+P or Cmd+Shift+P) and type "Preferences: Configure User Snippets".

Choose a Language: You'll be prompted to select a language for your snippet (e.g., javascript.json, python.json, etc.). This ensures the snippet is only available for that specific language. You can also create a "Global Snippets" file if you want the snippet to be accessible across all languages.

Define the Snippet: Snippets are defined in JSON format. Each snippet has a name, a prefix (the shortcut you'll type to trigger the snippet), a body (the code to be inserted), and an optional description.

Example (JavaScript):
{
  "For Loop": {
    "prefix": "forl",
    "body": [
      "for (let i = 0; i < $1; i++) {",
      "  $0",
      "}"
    ],
    "description": "For loop with index"
  }
}
In this example:

"For Loop": The name of the snippet (for your reference).
"forl": The prefix. Typing "forl" and pressing Tab will insert the snippet.
"body": The code to insert. $1, $2, etc. are tabstops (placeholders). $0 is the final cursor position.
"description": An optional description shown in the IntelliSense suggestions.
Using Snippets:

Type the Prefix: In a file of the correct language type, start typing the prefix you defined (e.g., forl).

Select the Snippet: VS Code's IntelliSense will suggest the snippet. Select it with the arrow keys or by clicking.

Use Tabstops: Press Tab to navigate between the tabstops ($1, $2, etc.) and fill in the values.

Variables:

Snippets can also utilize variables like $TM_FILENAME, $CURRENT_YEAR, etc. For a full list, see the VS Code documentation.

Example with Variables (Python):
{
  "New Python File": {
    "prefix": "newpy",
    "body": [
      "#!/usr/bin/env python3",
      "# -*- coding: utf-8 -*-",
      "",
      "# ${TM_FILENAME}",
      "# Created by: ${USER} on ${CURRENT_YEAR}-${CURRENT_MONTH}-${CURRENT_DATE}"
    ]
  }
}
By mastering snippets, you can significantly reduce repetitive typing and ensure consistency in your code. Experiment with creating your own snippets for commonly used code patterns and watch your coding efficiency soar.