这里以创建一个 javascript 代码片段为例:

1.首先可以打开一个javascript的文件(或在当前打开文件中)按快捷键Ctrl+Shift+P打开命令输入 snippet : (也可以点击文件=>首选项=>用户代码片段)

vscode如何写javascript代码 vscode怎么编写javascript_编辑器

2.选择选项后会出现一个语言列表用以选择给哪种语言创建代码段,这里以设置javascript的Console.WriteLine代码段为例,其他语言方法是一样的.
选择javascript后会自动打开一个JSON格式的配置文件.Visual Studio Code默认已经给出Demo了.照葫芦画瓢即可.

{
	// Place your snippets for javascript 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"
	// },
}

参数解释:

prefix      :这个参数是使用代码段的快捷入口,比如这里的log在使用时输入log会有智能感知.
body        :这个是代码段的主体.需要设置的代码放在这里,字符串间换行的话使用\r\n换行符隔开.注意如果值里包含特殊字符需要进行转义.
        多行语句的以,隔开
$1          :这个为光标的所在位置.
$2          :使用这个参数后会光标的下一位置将会另起一行,按tab键可进行快速切换,还可以有$3,$4,$5.....
description :代码段描述,在使用智能感知时的描述

修改为以下内容:

{
	// Place your snippets for javascript 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:
	"Page Header": {
		"prefix": "ducx",
		"body": [
			"/**",
			" * $1",
			" * ",
			" * @author ducx",
			" * @created $CURRENT_YEAR/$CURRENT_MONTH/$CURRENT_DATE $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND",
			" */",
			"$2"
		],
		"description": "page header"
	}
}

保存之后,打开一个 js 文件,输入前缀 ducx 出现快捷提示窗后回车,此时已经生成了我们自定义的代码片段结构,依次按 tab 

/**
 * 
 * 
 * @author ducx
 * @created 2018/08/31 17:08:37
 */

基本语法补充说明

  • prefix 触发快捷提示的字符串前缀
  • body 代码片段主体
  • $num 是每次按 tab 键光标移动对位置,$0 表示光标最后停留位置,不设置 $0,这光标最终位置在文件末尾;
  • ${2:默认文本} 跳转到指定位置到同时选中默认文本,方便修改;
  • $CURRENT_YEAR是引用的 snippets 内置变量,其它还有:
  • TM_FILENAME 当前文件名
  • TM_FILENAME_BASE 当前文件名,不带扩展名
  • TM_DIRECTORY 当前文件所属目录的绝对路径
  • TM_FILEPATH 当前文件的绝对路径
  • CURRENT_YEAR 当前年份
  • CURRENT_YEAR_SHORT 当前年份,最后两位数字
  • CURRENT_MONTH 当前月份数字形式,两位表示
  • CURRENT_MONTH_NAME 当前月份英文形式,如 July
  • CURRENT_MONTH_NAME_SHORT 当前月份英文缩写形式,如 Jul
  • CURRENT_DATE 当前日
  • CURRENT_DAY_NAME 当前星期,如 Monday
  • CURRENT_DAY_NAME_SHORT 当前星期缩写形式,如 Mon
  • CURRENT_HOUR 当前小时,24小时格式,两位表示
  • CURRENT_MINUTE 当前分钟,两位表示
  • CURRENT_SECOND 当前秒,两位表示
  • \n 换行
  • \t 制表符
  • description 快捷提示窗对该代码片段对描述