如何在 VS Code 中创建预设的代码片段

在项目开发中,我们经常需要新建文件,而这些初始化这些文件又需要敲出很多相同的代码,比如我们新建一个 .vue 的文件,需要我们在写正式的功能代码之前,完成以下初始化代码:

<script setup lang='ts'>
</script>

<template>
  <div>

  </div>
</template>

<style scoped>

</style>

为了不用每次都从其它文件中拷贝来拷贝去,我们的代码编辑器帮我们实现了一个代码片段的功能,即通过输入一个简单的命令来实现快速完成一段预制代码编写的目的。

下面我们来看看如何实现这样一个命令来智能生成自己想要的代码片段。

1. 创建 CODE-SNIPPETS 类型文件

打开 VS Code 软件,在顶部菜单选择 文件 —> 首选项 —> 配置用户代码片段,有“新建全局代码片段文件”和“新建“当前项目”文件夹的代码片段文件”两个选择项,不同之处在于适用范围是全局还是当前某个项目,创建的文件位置也不一样,如果是当前项目的,保存在项目根目录下 .vscode 文件夹下。

2. 编辑代码片段文件

点击新建代码片段文件后,我这里选择的适用范围是当前项目,生成的文件里面默认包含的内容如下:

{
    // Place your LeadTechMS 工作区 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"
    }
}

文件里面有效内容是一个 JSON 对象,键名就是该代码片段的名称,在输入命令字符时显示在右侧的提示里。值里面又是另外一个对象,主要有四个属性:scopeprefixbodydescription

  • scope:代码片段在什么类型文件里适用,如果不指明,可移除该属性
  • prefix:输入的命令字符
  • body:里面是一个数组,包含即要生成的代码,以字符串数组的形式组成
  • description:描述性文字,可随便写

以下是我编辑好的代码片段文件

{
    "一个测试代码片段命令": {
        "prefix": "test",
        "body": [
            "<template>",
            "\t<div>",
            "\t\t<span>test snippets</span>",
            "\t</div>",
            "</template>"
        ],
        "description": "随便玩玩代码片段"
    }
}

3. 测试代码片段是否生效

编辑好代码片段文件后保存,无需重启编辑器,新建一个文件,未指明文件类型,在文件中输入 test,即出现生成代码片段的智能提示,此时回车即可

如何实现代码高效,除了对代码非常熟,敲键盘的速度比别人快,还得要借助工具。工欲善其事必先利其器。

评论

还没有评论...留下你的评论!

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Sidebar