Boost Your Productivity: How to Create and Use Custom Snippets in VS Code

shanshaji

Shan

Posted on April 1, 2023

Boost Your Productivity: How to Create and Use Custom Snippets in VS Code

As a developer, you might find yourself frequently using the same code patterns or syntax. Repeatedly typing out the same code can be tedious and can slow down your workflow. This is where snippets come in handy.

Visual Studio Code (VS Code) provides a built-in feature for defining and using snippets. Snippets are predefined templates of code that you can insert into your code file using a simple keyboard shortcut. In this article, we’ll explore how to create and use snippets in VS Code.

Defining Snippets

VS Code provides an easy way to create and define your own snippets. You can define snippets either for a specific language or for all languages. To create or edit your own snippets, go to the Command Palette by pressing Ctrl+Shift+P (Windows, Linux) or Cmd+Shift+P (macOS), and then search for "Configure User Snippets". Selecting this option will bring up a dropdown menu that allows you to choose a language-specific snippets file or a global snippets file.

Snippets files are written in JSON format, which supports C-style comments, and can define an unlimited number of snippets. Snippets support most TextMate syntax for dynamic behavior and can intelligently format whitespace based on the insertion context.

Let’s look at an example of defining a snippet for a JavaScript for loop:

// in file 'Code/User/snippets/javascript.json'
{
  "For Loop": {
    "prefix": ["for", "for-const"],
    "body": ["for (const ${2:element} of ${1:array}) {", "\t$0", "}"],
    "description": "A for loop."
  }
}

Enter fullscreen mode Exit fullscreen mode

In this example, For Loop is the name of the snippet. It will be displayed via IntelliSense if no description is provided. The prefix property defines one or more trigger words that display the snippet in IntelliSense. Substring matching is performed on prefixes, so in this case, fc could match for-const. The body property is one or more lines of content, which will be joined as multiple lines upon insertion. Newlines and embedded tabs will be formatted according to the context in which the snippet is inserted. Finally, the description property is an optional description of the snippet displayed by IntelliSense.

Additionally, the body of the example above has three placeholders (listed in order of traversal): ${1:array}, ${2:element}, and $0. You can quickly jump to the next placeholder with Tab, at which point you may edit the placeholder or jump to the next one. The string after the colon : (if any) is the default text, for example element in ${2:element}. Placeholder traversal order is ascending by number, starting from one; zero is an optional special case that always comes last and exits snippet mode with the cursor at the specified position.

Using Snippets

Once you’ve defined your snippets, you can start using them in your code. To insert a snippet, simply type the prefix in your code file and press Tab. The snippet will then be inserted into your code with the cursor placed at the first placeholder. You can then use Tab to jump to the next placeholder or use Shift+Tab to jump to the previous one.

For example, if we had the "For Loop" snippet defined as above, we could use it in our JavaScript file by typing for and then pressing Tab. The snippet would be inserted into the code, and we could then fill in the placeholders as needed.

More Detailed Example

If you're interested in using the 'Freezed' package in Flutter, I've created a handy VS Code extension that provides code snippets to speed up your development process. You can find the extension on GitHub at https://github.com/ArkrootHQ/freezed-snippets, and it's completely free to use. If you have any suggestions or ideas for improving the extension, feel free to contribute to the project. Your contributions are always welcome and greatly appreciated!

Here's a quick overview of the snippets currently included in the extension.

{
  "Part statement": {
    "prefix": "pts",
    "body": ["part '${TM_FILENAME_BASE}.g.dart';"],
    "description": "Creates a filled-in part statement"
  },
  "Part 'Freezed' statement": {
    "prefix": "ptf",
    "body": ["part '${TM_FILENAME_BASE}.freezed.dart';"],
    "description": "Creates a filled-in freezed part statement"
  },
  "Freezed Data Class": {
    "prefix": ["fdataclass", "fdc"],
    "body": [
      "@freezed",
      "class ${1:DataClass} with _$${1:DataClass}{",
      "  const factory ${1:DataClass}(${2}) = _${1:DataClass};",
      "}",
      "factory ${1:DataClass}.fromJson(Map<String, dynamic> json)",
      "=> _$${1:DataClass}FromJson(json);"
    ],
    "description": "Freezed Data Class"
  },
  "Freezed Union": {
    "prefix": "funion",
    "body": [
      "@freezed",
      "class ${1:Union} with _$${1:Union}{",
      "  const factory ${1:Union}.${2}(${4}) = ${3};",
      "}"
    ],
    "description": "Freezed Union"
  },
  "Freezed Union Case": {
    "prefix": "funioncase",
    "body": ["const factory ${1:Union}.${2}(${4}) = ${3};"],
    "description": "Freezed Union Case"
  }
}
Enter fullscreen mode Exit fullscreen mode

Here is an explanation of each snippet:

  • "Part statement": inserts a filled-in "part" statement for the current file.
  • "Part 'Freezed' statement": inserts a filled-in "part" statement for the generated Freezed file.
  • "Freezed Data Class": creates a new Freezed data class with a constructor and a "fromJson" factory method.
  • "Freezed Union": creates a new Freezed union with a specified number of cases.
  • "Freezed Union Case": inserts a new case into an existing Freezed union.

Conclusion

Snippets are a powerful feature in VS Code that can greatly increase your productivity as a developer. By defining your own snippets, you can save time

💖 💪 🙅 🚩
shanshaji
Shan

Posted on April 1, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related