VScode添加自定义代码片段

一、问题描述

我们在写代码或者创建文件的时候,中总会遇到一些重复性的代码,如果能一键生成模板代码,那就可以提高写文章或者编写代码的效率。比如在VScode中创建html文件时后,按!+tab时,就可以生成模板代码。如下:

#按`!+tab`时,生成代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
</html>

我们可以通过丰富这个模板,然后创出适合自己的模板代码。具体如下:

二、打开snippets

1、打开html.json编辑页面

F1或者按ctrl+shift+p组合键打开搜索框,然后搜索snippets,选择configure user snippets

然后再输入html,搜索出html.json后,点击html.json

最后打开html.json编辑页面,编辑模板

2、编辑模板

把模板部分放在{}内,如图所示:

代码如下:

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

	"my vue html code": {
		"prefix": "html",
		"body": [
			"<!DOCTYPE html>",
			"<html lang='en'>",
			"<head>",
			"	<meta charset='UTF-8'>",
			"	<meta name='viewport' content='width=device-width, initial-scale=1.0'>",
			"	<script src='../lib/vue.js'></script>",
			"	<title>${1}</title>",
			"</head>",
			"<body>",
			"	<div id='app'>",
			"",
			"	</div>",
			"",
			"	<script>",
			"		const app = new Vue({",
			"			el: '#app',",
			"			data: {",
			"				${2}",
			"			}",
			"		})",
			"	</script>",
			"</body>",

			"</html>",
		],
		"description": "我的html内容模板"
	}
}

注意,这里有些编辑的小技巧,在模板中是字符串,需要添加很多的双引号,此时,可以用alt+shift+鼠标选中需要编辑的点,然后按end跳到行最后,如视频所示:

3、最终效果

posted @ 2020-10-25 21:08  xyztank  阅读(455)  评论(0编辑  收藏  举报