代码片段,指的是能够帮助输入重复代码模式,比如初始页面的模板。通过 snippet ,我们仅仅输入一小段字符串,就可以在代码片引擎的帮助下,生成预定义的模板代码,接着我们还可以通过在预定义的光标位置之间跳转,来快速补全模板。
有三种方法:
通过快捷键「Ctrl + Shift + P」打开命令窗口(All Command Window),输入「snippet」,点选「首选项:配置用户代码片片段」
点击界面最左侧竖栏(也即活动栏)最下方的齿轮按钮,在弹出来的菜单中点选「用户代码片段」
通过文件 > 首选项 > 用户代码片段
{
// 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": "javascript,typescript",
// "prefix": "log",
// "body": [
// "console.log('$1');",
// "$2"
// ],
// "description": "Log output to console"
// }
}
为空意为适用所有语言
\$num
是每次按 tab 键光标移动对位置,\$0
表示光标最后停留位置,不设置 $0,这光标最终位置在文件末尾;\${2:默认文本}
跳转到指定位置到同时选中默认文本,方便修改;\n
换行\t
制表符这里以前言中的 “qbr” 举例
{
// 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:
"create react component": {
// "scope": "javascript,typescript",
"prefix": "qbr",
"body": [
"import { useState } from \"react\"",
"",
"const ${1:Demo} = () => {",
"\treturn <div>$2</div>",
"}",
"export default ${1:Demo}"
],
"description": "Log output to console"
}
}
效果
输入快捷键qbr,回车后生成代码片段如下
由于${1:Demo}
包裹了两处,默认会同时选中,便于修改
修改完毕后按下Tab键,由于$2
,光标移入到第4行的div标签中