vscode:快捷输入代码片段

背景

每次调试代码输入 console.log() 的时候都会想,有没有什么指令我按下了就能生成这行代码,甚至更多我想自定义的代码,然后就去搜了搜果然有,vscode 提供了自定义代码片段的功能。

步骤

打开 vscode,点击 Preferences -> Configure User Snippets
在这里插入图片描述
可以看到有许多的提示
在这里插入图片描述
前面两个是我自定义建的,新建有三种方式:

  1. 在列表中选择一个语言【全局对某种语言有效】
  2. New Global Snippets file【全局有效】
  3. New Global Snippets file for ‘项目名称’【项目有效】

列表中的第一行就是我通过方式2建立的,第一行就是我通过方式1建立的,其实没啥大差别,最终默认生成都是一份文件。

{
    
    
	// 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"
	// }
}

我们对文件稍微改造一下

{
    
    
	"Print to console": {
    
    
		"prefix": "ll",
		"body": [
			"console.log('测试-$2', $1)",
		],
		"description": "Log output to console"
	}
}

这时候输入 ll,我们看下效果
在这里插入图片描述
在这里插入图片描述
$1 就是生成后光标默认的位置,按下 tab 还可以跳到 $2 的位置,$0 是光标最后的位置。
也可以这样占位${1:label} ,生成的结果是这样,可以直接输入进行覆盖或使用这个默认占位符。
在这里插入图片描述

html demo

{
    
    
	"html-demo": {
    
    
		"scope": "html,vue-html",
		"prefix":"html",
		"body": [
			"<!DOCTYPE html>",
			"<html lang=\"en\">",
			"",
			"<head>",
			"  <meta charset=\"UTF-8\">",
			"  <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">",
			"  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">",
			"  <title>demo</title>",
			"</head>",
			"",
			"<body>",
			"  <div id=\"app\"></div>",
			"</body>",
			"",
			"<script></script>",
			"</html>",
		],
		"description": "html and vue model"
	}
}

注意:生成引号要加转义符 \
输入 html 则生成:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>demo</title>
</head>

<body>
  <div id="app"></div>
</body>

<script></script>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_43972437/article/details/130974276
今日推荐