当前位置:网站首页>Use of snippets in vscode (code template)

Use of snippets in vscode (code template)

2022-07-05 05:03:00 Fierce chicken

VSCode in snippets Use ( The code template )

Sometimes in use VSCode When front-end coding, there are always some code segments that need to be written repeatedly , At this time, use some code templates (snippets), Trigger... Through the specified character sequence snippets, Quickly entering a piece of code with a fixed template will improve the coding efficiency

built-in Snippets

VSCode It also comes with some snippets, Typical is JavaScript Medium for

 Use the built-in snippets

If you want to see what are the built-in code templates , Can pass Command Palette see :

Click the gear pattern in the lower left corner , And then find Command Palette Options ( Or use shortcut keys Ctrl + Shift + P), stay VSCode A search box appears at the top of the window to enter Insert Snippets You can see

To pass the Insert Snippets Command to view a language snippet when , The current editing language must be snippet The conditions of the corresponding language , To find the corresponding language snippet. alike , Only in the code reminder of the corresponding language can there be corresponding snippets remind . For example, if you want to find JS Of snippets, The currently open file is .html Type of , Then if the current editing position is <script> Inside , Input Insert Snippets You can find it JS Of snippet; Or the currently edited file is .js, Input Insert Snippets You can also find JS Of snippet. This is because snippet It has a scope snippet scope),snippet The scope of action is either some ( some ) Language , Or someone ( some ) project , This is not repeated here , Details can be found in https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-scope

 Check the built-in snippets

The directory of these configuration files is :
VSCode The installation directory \resources\app\extensions\ Corresponding language name \snippets\

download Snippets

Download here refers to downloading with snippets Plug in for , Can be in VSCode Plug in market search @category:"snippets"

Customize Snippets

Here we use CSS Code, for example : Before a simple front-end page layout , Generally, the internal and external margins of label elements will be cleared uniformly , So the following code blocks are often used

* {
    
	margin: 0;
    padding: 0;
}

For this purpose, I want to configure a snippet, Here we need to find CSS snippet Configuration file for : find VSCode The gear icon in the lower left corner , Find... In the menu “User Snippets” Options , choice CSS( Or the top menu File > Prenferences > User Snippets)
 Find the configuration file

Opened a css.json After the document , You can see a long comment , Read the notes carefully and enter as required You can configure your own code template , Not to mention the details of the rules , First, implement the above-mentioned method of clearing the inner and outer margins CSS style

Follow the notes , Add the following and save

"Clear all elements' margin and padding": {
    
    "prefix": "cmp",
    "body": [
        "* {",
        "\tmargin: 0;",
        "\tpadding: 0;$0",
        "}"
    ],
    "description": "Clear all HTML elements' default margin and padding"
}

prefix The text that represents the trigger code segment , So it needs to be the same as input cmp Trigger , The effect is as follows
 Use custom snippets

snippets Configuration rules

When opening the user snippets When the profile for , You can always see a comment , According to this note, you can usually write your own snippet 了 , And my description of the following content is based on the content of this note

// Place your snippets for css here. Each snippet is defined under a snippet name and has a prefix, body and
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the
// same ids are connected.
// Example:
// “Print to console”: {
// “prefix”: “log”,
// “body”: [
// “console.log(’$1’);”,
// “$2”
// ],
// “description”: “Log output to console”
// }

Profile type

snippet The configuration file is JSON file , Allow to use C Notes on language style , It is allowed to define an unlimited number of snippet

The basic structure

Single snippet The basic structure of the configuration is as follows :

//  Angle brackets contain content to indicate custom content 
"<snippet name>": {
    
    "prefix": "<triggerText>",
    //  If the template has multiple lines , Should be assigned with a string array , An element represents a line of content 
    "body": "<template>",
    "description": "<description of this snippet>"
}

Multiple configurations are separated by commas

First one snippet The configuration needs to specify a name , Then assign an object to this item
Object contains three parts :prefixbodydescription

  • prefix Is designated Used to trigger snippet The text of , For example, the clearance of the inner and outer margins of the elements configured above sippet, The use of prefix yes cmp(clear margin and padding). This can be configured according to your preferences , It's mainly easy to remember , After all, configuration snippet To improve coding efficiency

  • body Is to specify the content of the code template , It can be assigned as Single string perhaps An array of strings
    When the template has only one line of content or only one line of code , You can directly assign this line of code as a string to body. For example, if you want to print quickly console.log("hello") This sentence , You can configure :

    "Print Hello to console": {
          
        "prefix": "hello",
        "body": "console.log('Hello');", //  Direct assignment statement string 
        "description": "Print Hello to console"
    }
    

    If the template is multi line content , Then you need to use a string array to assign ( If above CSS Example ), One of the elements represents a line of content . The white space character can use the escape character ( If above CSS Example ), And if you apply white space characters directly , Only spaces can be applied ( You can't apply tabs directly )

  • description Is to specify the description of the snippet The function of the template or the field of the template content , Its content will appear in relevant reminders

    description Appear in the snippet Description

    description Appear in the code reminder

Use of special structures

body Part of the content can use some special structures to control the cursor position and inserted text . The following describes the default comments in the configuration file tabstops and placeholders

tabstops

When outputting a snippet when , If snippet Of body Defined tabstops, Then you can. adopt Tab Key to jump the cursor position to a specific position , It is convenient to modify the generated template

tabstops use $0, $1, $2, ...... identification , Numbers indicate the order in which they are accessed , and $0 It indicates the last cursor position , also Of the same number tabstops It's related ( In other words, there will be multiple cursors in multiple associated positions at the same time )

Look at the following example :

//  Add to JavaScript Of snippets In profile 
"Test tabstops": {
    
    "prefix": "tts",
    "body": "$0two($2);one($1);three($3);one($1)",
    "description": "a test for tabstops"
}

At the beginning of the above example, there will be two cursors in two one() Brackets ; Then press once Tab after , There will be a cursor in two() In brackets ; The second time according to the Tab after , The cursor will be in three() In brackets ; Press again Tab, The cursor will run to the front of this line of code , because $0 Identifies the last position the cursor reaches ( If you don't set $0 Will arrive by default body The last position of the content , Here is the end of the generated line of code )

tabStops Operation effect of

So far, it should be understandable tabstops The meaning of this title , In fact, that is “ Press tab Where the rear cursor stops
In addition, you can Press Shift+Tab Go back to the previous tabstops The location of , But note that if you arrive $0, That is to say snippet There are other operations after the last position of the cursor in the ( Include press Tab), You can't go back to the previous tabstops Location.

placeholders

placeholders It's with value tabstops, The value will be inserted into the code as text and selected , In this way, you can easily modify the content of the code template

The most typical example is the one built in at the beginning of the article for loop JS snippet, Here I'll repeat it a little bit, for example

"Test placeholders": {
    
    "prefix": "flt",
    "body": [
        "for(let ${1:index} = 0; ${1:index} < ${2:array}.length; ${1:index} ++) {",
        "\t${4:const} ${3:element} = ${2:array}[${1:index}];",
        "\t$0",
        "}"
    ],
    "description": "a test for placeholders using for loop"
}

At the beginning , There are multiple selected index, You can modify all at the same time index For what you want ; Then press once tab, Select all at the same time array, At this time, you can also modify all the selected contents at the same time ; Press for the second time tab Just choose element; Press the third time , That's it const; Press again and you'll get to the last position $0( If you don't set $0 Will arrive by default body The last position of the content , Here is after the right curly bracket )

placeholders Operation effect of

snippet Syntax allows more than the above special structures to be used tabstops and palceholders Configuration of , And others , Details refer to https://code.visualstudio.com/docs/editor/userdefinedsnippets#_snippet-syntax

Reference resources :Snippets in Visual Studio Code

原网站

版权声明
本文为[Fierce chicken]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140623557459.html