vscode 快速创建模板代码

3,052 阅读1分钟

场景

vscode 创建一个新的页面,有些内容配置都是固定一样的,一般都是手写或自己copy一份文件,然后删减,留下需要的模板内容。是否有快速生成这种模板的快捷方式呢?

解决方案:

vscode 可以自定义用户代码片段,只需要执行自定义命令即可就能生成对应的代码片段

步骤:

1. 点击左下角的设置,选择“用户代码片段”

2. 选中“新建全局代码片段文件”,并自定义一个文件名

3. 会看到自动生成的如下代码片段

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

可以根据以上的例子参考,写一个自己的模板代码,这里以vue中使用tsx为例子:

{
  "Print to console": {
    "prefix": "vtsx",//代码片段的命令
    "body": [//body里面就是模板代码片段
      "import { defineComponent } from 'vue'",
      "",//换行
      "export default defineComponent({",
      "name: 'Hello',",
       "setup(props, { emit }) {",
          "return () => {",
            "return (",
              "<div>Hello World</div>",
            ")",
          "}",
        "},",
      "})",
    ],
    "description": "tsx and vue hook template"
  }
}

直接保存就可以了

4. 模板建好之后,新建一个index.tsx文件,在文件中输入vtsx,回车就能生成刚配置的模板代码

回车后显示如下:

image.png