把重复利用的代码模板定义成自己的代码片段,提高编码效率和减少不必要的错误产生
打开VS code,“文件-首选项-用户代码片段”(file-preference-User Snippets)
在下拉列表中选择html文件,此时在VS code的应用数据文件夹内自动新建了一个名为html.json的文件,我们在这个json文件中定义我们的代码片段
我们需要首先定义snippet name,在snippet name中,prefix和body是必不可少的两个字段(The prefix is what is used to trigger the snippet and the body will be expanded and inserted.)
"demohtml": {
"scope": "html",
"prefix": "demohtml",
"body": [
"",
"",
"<head>",
"\t",
"\t<title>${1:Title}title>${2}",
"head>",
"<body>",
"\t${3}",
"body>",
"html>",
"${0}"
],
"description": "create a html frame"
}
{
// Place your 全局 snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and
// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope
// is left empty or omitted, the snippet gets applied to all languages. 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": {
"scope": "html",
"prefix": "demohtml",
"body": [
"",
"",
"",
"\t",
"\t${1:Title} ${2}",
"",
"",
"\t${3}",
"",
"",
"${0}"
],
"description": "自定义的html"
}
}
语法:
在body中,使用转义字符\来书写制表符Tab、双引号"等内容;
使用${num: default name}来定义输入位置,按下Tab键来递进光标到下一个;
num的值为0,1,2,3…。0为光标的最终位置,1,2,3…决定了光标的顺序位置;
default name是默认值,可按下Tab不编辑直接跳过。
代码片段分为两种:全局和特定,这意味着我们可以定义适用于多种文件类型的代码片段,也可以定义仅仅针对于一种文件类型的代码片段。
全局代码片段的文件后缀名为.code-snippets,在用户代码片段下拉列表中,最上方有一个“新建全局代码片段文件”。
全局代码片段的语法规则和特定代码片段的语法规则一致,唯一区别在于其增加了一个字段scope,用于指定该规则适用于何种语言:
{
"For_Loop": {
"prefix": "for",
"scope": "javascript,typescript",
"body": [
"for (const ${2:element} of ${1:array}) {",
"\t$0",
"}"
],
"description": "For Loop"
},
}
"link template": {
"prefix": "${0}"
],
"description": "complete css link"
},
"script template": {
"prefix": "