When it comes to the IDE used for front-end development, I believe that many students’ first reaction will be VSCode. Yes, Microsoft’s VSCode quickly took the top spot in the IDE market with its excellent performance and powerful features. By 2021, 71% of developers worldwide (not just front-end development) will be using VSCode. Knowing the tools we work with most in our daily development and tapping into the power VSCode has to offer will make our development more productive. This article explains what VSCode Snippets are and how to improve our development happiness.

What is VSCode Snippets

The Snippet: fragment. VSCode Snippets, meaning predefined Snippets or code templates in VSCode, for quick code completion.

You may not have heard of VSCode Snippets, but you must have used them in your development. The most common one is probablyconsole.logandThe for loop. For example, when you typelog“, it will prompt you to press Tab or Enter,logIt will become aconsole.log(), the cursor is positioned between the brackets.

classification

According to the source points

VSCode Snippets include built-in Snippets, extended Snippets, and custom Snippets. Contributes.p shortcut to open the command palette, select Insert Snippets and see the current file to all the Snippets of the language.

The console.log and for loops mentioned earlier are built in Snippets. In addition, Emmet Snippets are built into VSCode, dealing with HTML, CSS, JSX, and so on.

Extended Snippets are the Snippets provided by VSCode Extension. We can do this by searching@categery:"snippets"To find the extension that provides the desired snippets.For example, if you installJavascript(ES6) code snippetsWith this extension, you can use many shortcut inputs.Custom Snippets, more on that later.

According to the scope of action

This includes global snippets (across projects, regardless of language), language-specific snippets (JS, TS, TSX, etc.), and snippets that are only valid for the current project (extension only open for that project or custom code-snippets files under.vscode).

To share snippets with multiple people, develop a VSCode Extension or create snippets under.vscode and submit them to the repository.

Let’s focus on customizing VSCode Snippets.

Custom Snippets

Let’s start with an example:

{
  "Print to console": {
    "scope": "javascript,typescript"."prefix": "log"."body": [
        "console.log('$1');"."$2"]."description": "Log output to console"}}Copy the code

As you can see, a snippet contains several key components:

  1. Name: aboveFor LoopAppears on the right side of the prompt panel entry, suggesting a special name that makes it easy to distinguish which snippet to use;
  2. Scope: The language that defines the snippet, which is displayed only when editing the file for the language;
  3. Prefix: When you input a character that matches prefix (substring matching is also ok, such as: inputfcCan matchfor-const), the snippet appears on the prompt panel;
  4. Body: The content of the template to be inserted. It can be a string or an arrayjoin('\n')Concatenated into a string for display. More on that later;
  5. Description: Describes the purpose of the snippet for yourself or others.

The content in the body follows the TextMate syntax, with the following points:

Tabstop

$Indicates the position to be located when you press Tab. If you press Tab several times, the position will be located in ascending order. But $0 is special, it is always the last position to be located, so in the for of loop above, the order of multiple Tab positions would be $1 -> $2 -> $0. Multiple tabs with the same value synchronize all position changes.

Placeholder

${2: Element} is a special form of Tab. Element is a placeholder character indicating that the element string is inserted at this position. The second Tab selects Element. Placeholder supports nesting, such as ${1:another ${2: Placeholder}}.

options

Placeholder can be set to specific options, allowing users to select from the options provided. Format for ${1 | one, two, three |}, option package with a pipe symbol, comma separated. After you insert the snippet and position it in the current Placeholder, a box pops up for the user to select.

variable

VSCode Snippets can use global variables as $name or ${name:default}. For details on what global variables can be used, refer to the official documentation.

If you want to write a snippet for the React Function component template, generate the component name based on the file name. For the simple version, you can write:

{
  "React Function Component": {
		"prefix": ["rfc"]."body": ["const $TM_FILENAME_BASE = () => {"."\treturn ("."\t\t$0"."\t);"."};."export default $TM_FILENAME_BASE;"]."description": "The React components"}}Copy the code

For example, if you want to retrieve the contents of the stickboard, use ${CLIPBOARD: defaultText}. When the contents of the stickboard are empty, defaultText will be used as the default value.

If the variable is not found, the variable name is inserted as plain text.

conversion

Variables and Placeholder can be converted before insertion, usually by regular matching for text replacement or formatting, in the form of

/<regexp>/<format|text>/options
Copy the code

To remove the suffix from a file name, write ${TM_FILENAME/(.*)\\.. ${TM_FILENAME_BASE} = ${TM_FILENAME_BASE}

If you want to name all uppercase processing, you can write ${TM_FILENAME/(. *) / ${1: / upcase}}.

In addition to regular matching and formatting, we can also use conditional statements to handle logic. Here’s an example found on StackOverflow:

{
  "color conditional": {
    "prefix": "_hex"."body": [
      "let color = '${1}';"."let hex = '${1/(white)/${1:? #fff:#000}/}';" / / if p]."description": "conditional color"}}Copy the code

If white is entered, pressing Tab will replace it with # FFF, otherwise with #000.

See the official documentation for more conversions, but I think regular matching, formatting, and conditional statements are enough for most everyday situations.

In actual combat

Since using React hooks, it has been specified in our project that all functions must be wrapped in useCallback. As a result, daily coding requires a lot of repeated input of useCallback. You can define the following snippet quick insert useCallback method:

{
  "useCallback wrap": {
    "prefix": "uc"."body": ["useCallback(() => {"."\t$0"."[])},"]."description": "Automatically create a useCallback"}}Copy the code

UseMemo is similar.

Another scenario is that we write the React component repeatedly with import ‘React’, const ComponentName, export Default ComponentName, etc. At this point we can extract this part into snippets and write multiple lines of code in an instant. Here’s a snippet I defined for you:

{
    "TS React FC": {
    "scope": "typescriptreact"."prefix": "comp"."body": [
      "import { FC } from 'react';".""."interface ${TM_FILENAME_BASE/(.+)/${1:/capitalize}/}Props {".""."}".""."const ${TM_FILENAME_BASE/(.+)/${1:/capitalize}/}: FC<${TM_FILENAME_BASE/(.+)/${1:/capitalize}/}Props> = (props) => {"."\treturn ("."\t\t$0"."\t);"."};.""."export default ${TM_FILENAME_BASE/(.+)/${1:/capitalize}/};"]."description": React Component Template}}Copy the code

If you have any useful or interesting snippets, please share them with me.

conclusion

  1. VSCode Snippets are predefined code templates that help you insert code quickly and make repetitive work easy.
  2. When working with snippets, you can first see if VSCode has snippets built in or if any extension provides snippets before customizing.
  3. The ability to customize snippets with Tab stop positions, Placeholder positions, options, variables, and transformations allows us to write flexible and useful code templates.

The resources

  1. www.ithome.com/0/567/643.h…
  2. Code.visualstudio.com/docs/editor…
  3. Macromates.com/manual/en/s…
  4. Stackoverflow.com/questions/5…