vscode如何创建代码段

862 阅读1分钟

1. 点击vscode左下角的设置按钮,在弹出面板中找到用户代码片段选项

01.png

2. 选择新建代码片段

02.png

3。在弹出输入框中,输入你要创建的模板名称

03.png

4. 按照对应模板输入你想设置的模板内容即可

05.png

{
	// 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:
	// "Print to console": {
	// 	"scope": "javascript,typescript",
	// 	"prefix": "log",
	// 	"body": [
	// 		"console.log('$1');",
	// 		"$2"
	// 	],
	// 	"description": "Log output to console"
	// }
	"Print to console": {
		"scope": "javascript,typescript",
		"prefix": "express", // 输入什么内容可以触发当前代码片段
		"body": [ // 当前 代码段所想展示的内容, 每一行显示的内容都是一个字符串
			"// 导入 express 模块", // 每一行结束的时候, 都要有一个逗号进行分割,
			"const express = require('express')",
			" ",	// 如果你想在你生成的代码中有一个空行,那么你必须有一个空的字符串作为占位
		    "// 创建 express 的服务器实例",
			"const app = express()",
			" ",
			"",
		    "// 启动当前服务器",
		    "app.listen(80, (req, res) => {",
			"  console.log('http://127.0.0.1')",
		    "})"
		],
		"description": "Log output to console" // 这是个描述信息
	}
}

5. 在新文件中输入刚才你设置的触发代码段前缀,即可快速生成模版

06.png

07.png