当前位置:网站首页>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

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

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)
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 
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 :prefix、body、description
prefixIs 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 ofprefixyescmp(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 efficiencybodyIs 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 tobody. For example, if you want to print quicklyconsole.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 )
descriptionIs 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

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 )

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 )

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
边栏推荐
- Pause and resume of cocos2dx Lua scenario
- Personal required code
- 2022 American College Students' mathematical modeling ABCDEF problem thinking /2022 American match ABCDEF problem analysis
- 【论文笔记】Multi-Goal Reinforcement Learning: Challenging Robotics Environments and Request for Research
- 2022 / 7 / 1 Résumé de l'étude
- 775 Div.1 C. Tyler and strings combinatorial mathematics
- 2022 U.S. college students' mathematical modeling e problem ideas / 2022 U.S. game e problem analysis
- 嵌入式数据库开发编程(零)
- AutoCAD -- dimension break
- 中国艾草行业研究与投资前景预测报告(2022版)
猜你喜欢

Grail layout and double wing layout

Django reports an error when connecting to the database. What is the reason

2021 higher education social cup mathematical modeling national tournament ABCD questions - problem solving ideas - Mathematical Modeling

3dsmax scanning function point connection drawing connection line

Unity parallax infinite scrolling background

XSS injection

LeetCode之单词搜索(回溯法求解)

UE4/UE5 虚幻引擎,材质篇,纹理,Compression and Memory压缩和内存

Ue4/ue5 illusory engine, material chapter, texture, compression and memory compression and memory

AutoCAD - feature matching
随机推荐
Download and use of font icons
2021 electrician cup idea + code - photovoltaic building integration plate index development trend analysis and prediction: prediction planning issues
2021 Higher Education Club Cup mathematical modeling national tournament ABCD problem - problem solving ideas
Use assimp library to read MTL file data
Unity card flipping effect
Lua wechat avatar URL
Emlog blog theme template source code simple good-looking responsive
《动手学深度学习》学习笔记
Emlog博客主题模板源码简约好看响应式
Establish cloth effect in 10 seconds
775 Div.1 C. Tyler and strings combinatorial mathematics
Rip notes [rip message security authentication, increase of rip interface measurement]
#775 Div.1 C. Tyler and Strings 组合数学
中国艾草行业研究与投资前景预测报告(2022版)
Unity synergy
Dotween usage records ----- appendinterval, appendcallback
django连接数据库报错,这是什么原因
AutoCAD - full screen display
669. Prune binary search tree ●●
Forecast report on research and investment prospects of Chinese wormwood industry (2022 Edition)