模板代码生成
开始之前
vue 文件,都会有一个基础模板,如果每次开发都从 0 开始编写,那效率太低了,所以需要一个模板代码生成工具,来生成基础模板代码。
vs Code 有自带的代码生成片段,Snippets
# 1. Snippets 介绍
用于自定义代码模板,在文件内输入设定好的模板名称即可使用代码模板。
Snippets 可以通过手动创建或从插件中导入来管理。手动创建的 Snippets 可以直接在编辑器中使用,而导入的 Snippets 需要先安装插件才能使用。
Snippets 是一种非常有用的编程工具,可以帮助开发者提高效率,减少错误,提高代码质量。
# 2、 Snippets 配置
# 2-1、 打开 vs Code 右下角的设置按钮,点击里面的用户代码片段

# 2-2、编辑器顶部会出现已有的代码片段,如果没有,则需要自己创建
代码片段可分为全局、项目、语言级别

# 2-3、新增代码片段
点击上图中的新代码片段即可新建自己的代码片段
- 新建代码片段名称
点击新代码片段,即可开始输入新的代码片段名称

- 配置代码片段
当打开用户 snippets 的配置文件时,总能看到一段注释,根据这段注释一般就可以写出自己的 snippet 了,接下来基于这段注释的内容展示如何写一个 snippet
{
// 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"
// }
}
基本结构
// 尖括号包含内容表示自定义内容
"<snippet name>": {
"scope": "<language>",
"prefix": "<triggerText>",
// 如果模板有多行,应该用字符串数组赋值,一个元素代表一行内容
"body": "<template>",
"description": "<description of this snippet>"
}
项目实例,写一个 vue3 的基础模板
{
"vue3 template": {
"prefix": "vue3-new",
"scope": "vue",
"body": [
"<template>",
" <div></div>",
"</template>",
"",
"<script lang=\"ts\" setup>",
"</script>",
"<style scoped lang=\"scss\"></style>"
],
"description": "Log output to vue3 base template"
}
}
snippet name
: 自定义内容名称
如上述示例,vue3 template
就是该 snippets 的名称
scope
: 该 snippet 适用的范围,可以是一个或多个,多个用逗号分隔
如果设置了该属性,那么该 snippet 只会在 vue 文件中触发。
在 JS 文件中,输入前缀,可以看见并不会触发 vue3 template 这个代码片段

在 VUE 文件中,输入前缀,可以看见会触发 vue3 template 这个代码片段

选中按下回车就生成了 vue3 最基础的模板

prefix
: 触发该 snippet 的前缀
如上诉示例,输入 vue3-new
或者V
开头 就会触发该 snippet
body
: 是指定代码模板内容
,这里可以赋值为单个字符串
或者一个字符串数组
。
当模板只有一行内容或者只有一行代码时,可以直接把这行代码作为字符串赋值给body
如果模板是多行内容,那么则需要用一个字符串数组来赋值(如上述例子),其中一个元素代表一行内容。其中的空白字符可以使用转义字符(如上述的例子),并且如果直接应用空白字符,只有空格可以应用(不可以直接应用制表符)
description
: 是指定描述该 snippet 的作用或者模板内容的字段,它的内容会出现在相关的提醒中language
: 该 snippet 适用的语言,可以是一个或多个,多个用逗号分隔
提示
更多配置请参考官方文档 (opens new window)