在 Visual Studio Code 中添加自定义的代码片段

本文介绍了如何在 Visual Studio Code 中创建和使用自定义代码片段,包括设置、编写和插入过程,以及代码片段的高级特性,如占位符、下拉选项和变量的使用,提高编码效率。
摘要由CSDN通过智能技术生成

无论是那个编辑器,如果能够添加一些自定义代码片段,能够大大提升代码的输入效率。

本文介绍如何在 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 字段为空
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值