无论是那个编辑器,如果能够添加一些自定义代码片段,能够大大提升代码的输入效率。
本文介绍如何在 Visual Studio Code 中添加自定义代码片段。
本文内容
Visual Studio Code 的代码片段设置
你可以在 Visual Studio Code 的菜单中找到代码片段的设置入口,在 File -> Preferences -> User Snippets 中。
▲ 打开用户代码片段设置
点开后,会让你选择做什么:
- 新建全局代码片段
- 新建适用于当前工作区的代码片段
- 新建特定于语言的全局代码片段
根据你的需要选择一个范围:
- 比如你需要在任何文件中都能够使用的代码片段,那么选择全局代码片段。
- 比如你需要仅在当前工作区生效的代码片段(例如我写博客是才会用到的博客片段),那么选择工作区代码片段。
- 如果是特定于语言的,那么选择自己需要的语言。
在新建全局代码片段和当前工作区的代码片段的时候,是需要自己指定名称的。
▲ 指定代码片段的名称
编写代码片段
无论你使用哪种方式新建代码片段,Visual Studio Code 都会帮你打开这个代码片段文件。整个文件一开始是被注释的状态,就像下面这样:
{
// Place your global 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"
// }
}
上面的注释,翻译一下是这样的:
可以将你的全局代码片段放到这里。每一个代码片段都由一个名称来定义,其值包含此代码片段的作用域(scope)、前缀(prefix)、代码片段的内容(body)与其描述信息(description)组成。
- scope 字段中填写以逗号分隔的作用域 Id,如果 scope 字段为空