VS Code自定义代码片段snippets

3,585 阅读1分钟

snippets语法

  • scope :代码片段的使用范围
  • prefix :代码片段名字,即输入此名字就可以调用代码片段。
  • body :这个是代码段的主体.需要编写的代码放在这里,     
  • $1 :生成代码后光标的初始位置.
  • $2 :生成代码后光标的第二个位置,按tab键可进行快速切换,还可以有$3,$4,$5.....
  • ${1,字符} :生成代码后光标的初始位置(其中1表示光标开始的序号,字符表示生成代码后光标会直接选中字符。)
  • description :代码段描述,输入名字后编辑器显示的提示信息。

新建代码片段

  • File -> preferences -> User Snippets -> 新建代码片段
  • 或者按快捷键: Ctrl + P, 然后输入: > snippets, 选择: 新建代码片段

添加tsvue代码片段

最终生成的代码为:

<template>
  <div>

  </div>
</template>

<script lang="ts">
import { Vue, Component, Emit, Inject, Model, Prop, Provide, Ref, Watch, PropSync } from 'vue-property-decorator'

@Component
export default class CustomComponent extends Vue {

}
</script>

tsvue 代码片段内容如下:

{
	// 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:
"ts vue single file": {
	"scope": "javascript,typescript, vue",
	"prefix": "tsvue",
	"body": [
		"<template>",
			"\t<div>",
			"\r",
			"\t</div>",
		"</template>",
		"\r",
		"<script lang='ts'>",
		"import { Vue, Component, Emit, Inject, Model, Prop, Provide, Ref, Watch, PropSync } from 'vue-property-decorator'",
		"\r",
		"@Component",
		"export default class ${1:name} extends Vue {",
		"\t$2",
		"}",
		"</script>",
		""
	],
	"description": "快速创建ts版本vue单文件组件"
}
}

最终效果如下: