search
HomeDevelopment ToolsVSCodeLet's talk about how to use snippets in VSCode to improve development efficiency!

VSCode支持自定义 snippets,可以极大提高开发效率。下面本篇文章就来给大家通过一个案例来学会 VSCode Snippets,希望对大家有所帮助!

Let's talk about how to use snippets in VSCode to improve development efficiency!

snippets 是片段的意思,VSCode 支持自定义 snippets,写代码的时候可以基于它快速完成一段代码的编写。【推荐学习:《vscode入门教程》】

Lets talk about how to use snippets in VSCode to improve development efficiency!

不只是 VSCode,基本所有的主流编辑器都支持 snipeets。

一个功能被这么多编辑器都支持,那肯定是很有用的,但是这功能大多数人都没用起来。

我之前写的 snippets 文章中讲了 snippets 支持的各种语法和配置方式,但是并没有用这些来做一个真实的案例。

所以,这篇文章就来讲一个真实的 snippets,基本用到了所有的 snippets 语法。能独立把它写出来,就可以说 snippets 已经掌握了。

我们还是先回顾下 VSCode 的 snippets 语法

snippets 基础

snippets 是这样的 json 格式:

{
    "alpha": {
        "prefix": ["a", "z"],
        "body": [
            "abcdefghijklmnopqrstuvwxyz"
        ],
        "description": "字母",
        "scope": "javascript"
    }
}
  • prefix 是触发的前缀,可以指定多个
  • body 是插入到编辑器中的内容,支持很多语法
  • description 是描述
  • scope 是生效的语言,不指定的话就是所有语言都生效

body 部分就是待插入的代码,支持很多语法,也是一种 DSL(领域特定语言)。

支持通过 $1、$2 指定光标位置:

"$1  xxxx",
"yyyy $2"

Lets talk about how to use snippets in VSCode to improve development efficiency!

可以多光标同时编辑:

"$1  xxxx $1"

Lets talk about how to use snippets in VSCode to improve development efficiency!

可以加上 placeholader,也可以做默认值:

"${1:aaa}  xxxx",
"yyyy ${2:bbb}"

Lets talk about how to use snippets in VSCode to improve development efficiency!

可以提供多个值来选择:

"${1|卡颂,神光,yck|}最帅"

Lets talk about how to use snippets in VSCode to improve development efficiency!

还提供了一些变量可以取:

"当前文件: $TM_FILENAME",
"当前日期: $CURRENT_YEAR/$CURRENT_MONTH/$CURRENT_DATE"

Lets talk about how to use snippets in VSCode to improve development efficiency!

而且还能对变量做正则替换:

"${TM_FILENAME/(.*)\\.[a-z]+/${1:/upcase}/i}"

Lets talk about how to use snippets in VSCode to improve development efficiency!

基本语法过了一遍,大家知道支持啥就行,后面我们来做个真实的案例,把这些用一遍就会了。

通过 command + shift + p,输入 snippets 然后选择一种范围:

Lets talk about how to use snippets in VSCode to improve development efficiency!

Lets talk about how to use snippets in VSCode to improve development efficiency!

snippets 有 project、global、language 3 种生效范围。我个人写 global 级别的比较多,项目和语言级别的也可以。

基础过完了,接下来我们就来写一个 snippets 吧。

实战案例

我最近在做 vue 的项目,写 router-link 比较多,所以封装了个 router-link 代码的 snippets。

我们先写个最简单的版本:

{
    "routerLink": {
        "prefix": "link",
        "body": [
            "<router-link to={ name:&#39;xxx&#39;, params: {id: 1} } target=&#39;_blank&#39;>link</router-link>"
        ],
        "description": "router-link 跳转"
    }
}

这个没啥好说的,就是根据前缀补全内容:

Lets talk about how to use snippets in VSCode to improve development efficiency!

然后在 name、id、链接文字处加三个光标,也就是 $1、$2、$3:

{
    "routerLink": {
        "prefix": "link",
        "body": [
            "<router-link to={ name: $1, params: {id: $2} } target=&#39;_blank&#39;>$3</router-link>"
        ],
        "description": "router-link 跳转"
    }
}

可以按 tab 键快速编辑其中变化的部分:

1Lets talk about how to use snippets in VSCode to improve development efficiency!

然后加上 placeholder:

{
    "routerLink": {
        "prefix": "link",
        "body": [
            "<router-link to={ name: &#39;${1:RouteName}&#39;, params: {id: ${2:id}} } target=&#39;_blank&#39;>${3:link}</router-link>"
        ],
        "description": "router-link 跳转"
    }
}

1Lets talk about how to use snippets in VSCode to improve development efficiency!

其实 target 部分也是可选的,这里我们用多选来做:

选项有两个,就是 target="_blank" 或者空格。

${3| ,target=\"_blank\"|}

所以 snippets 就变成了这样:

{
    "routerLink": {
        "prefix": "link",
        "body": [
            "${4:link}"
        ],
        "description": "router-link 跳转"
    }
}

1Lets talk about how to use snippets in VSCode to improve development efficiency!

跳转地址大多数是和当前文件名有关,比如 XxxYyyZzzList 跳转 XxxYyyZzzDetail 的比较多。

所以我们默认值取当前文件名,用 TM_FILENAME 变量(所有可用变量可以在 vscode 官网查):

${1:$TM_FILENAME}

现在的 snippets:

{
    "routerLink": {
        "prefix": "link",
        "body": [
            "${4:link}"
        ],
        "description": "router-link 跳转"
    }
}

效果是这样:

1Lets talk about how to use snippets in VSCode to improve development efficiency!

确实把文件名填上去了,但是还要手动改,能不能填上去的就是改了之后的呢?

可以,变量支持做 transform,也就是正则替换:

XxxList.vue 要取出 Xxx 来,然后拼上 Detail,这样的正则不难写:

用 js 写是这样的:

&#39;XxxList.vue&#39;.replace(/(.*)List\.vue/,&#39;$1Detail&#39;)

1Lets talk about how to use snippets in VSCode to improve development efficiency!

在 snippets 里也差不多,只不过用 / 分开:

${TM_FILENAME/(.*)List\\.vue/$1Detail/i

所以 snippets 就变成了这样:

{
    "routerLink": {
        "prefix": "link",
        "body": [
            "${4:link}"
        ],
        "description": "router-link 跳转"
    }
}

填入的代码都是替换好了的:

1Lets talk about how to use snippets in VSCode to improve development efficiency!

链接的内容我们希望用选中的内容,这个也有变量,就是 TM_SELECTED_TEXT。

1Lets talk about how to use snippets in VSCode to improve development efficiency!

最后,我们希望 router-link 这个标签也可以变,而且改的时候开闭标签可以一起改。

这个要用多光标编辑,指定多个 $x 为同一个数字就行。

<${5:router-link}></${5:router-link}>

效果就是这样的:

1Lets talk about how to use snippets in VSCode to improve development efficiency!

这就是最终的 snippets,所有 snippets 语法都用了一遍。

完整 snippets 如下,大家可以在 VSCode 里用用看,用起来体验还是很爽的:

{
    "routerLink": {
        "prefix": "link",
        "body": [
            "<${5:router-link} to={ name: '${1:${TM_FILENAME/(.*)List\\.vue/$1Detail/i}}', params: {id: ${2:id}} } ${3| ,target=\"_blank\"|}>${4:$TM_SELECTED_TEXT}"
        ],
        "description": "router-link 跳转"
    }
}

总结

基本所有主流编辑器都支持 snippets,也就是配置代码片段来提高开发效率,VSCode 也不例外,这是一个很有用的功能。

VSCode snippets 支持 global、project、language 3 种生效范围。我个人用全局的比较多。

它也算是一种 DSL 了,支持很多语法,比如指定光标位置、多光标编辑、placeholder、多选值、变量、对变量做转换等语法。

  • 指定光标位置:$x
  • 多光标编辑:$x $x
  • 指定 placeholder 文本:${x:placeholder}
  • 指定多选值:${x|aaa,bbb|}
  • 取变量:$VariableName
  • 对变量做转换:${VariableName/正则/替换的文本/}

我们写了一个 router-link 的 snippets,综合运用了这些语法,过一遍就会了。

能自己定义适合自己的 snippets,对于提高开发效率是很有帮助的。如果没写过,不妨从今天开始试一下吧。

更多关于VSCode的相关知识,请访问:vscode教程!!

The above is the detailed content of Let's talk about how to use snippets in VSCode to improve development efficiency!. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Visual Studio and VS Code: Understanding Their Key DifferencesVisual Studio and VS Code: Understanding Their Key DifferencesApr 19, 2025 am 12:16 AM

VisualStudio is suitable for large-scale projects and enterprise-level application development, while VSCode is suitable for rapid development and multilingual support. 1. VisualStudio provides a comprehensive IDE environment and supports Microsoft technology stack. 2.VSCode is a lightweight editor that emphasizes flexibility and scalability, and supports cross-platform.

Is Visual Studio Still Free? Understanding the AvailabilityIs Visual Studio Still Free? Understanding the AvailabilityApr 18, 2025 am 12:05 AM

Yes, some versions of VisualStudio are free. Specifically, VisualStudioCommunityEdition is free for individual developers, open source projects, academic research, and small organizations. However, there are also paid versions such as VisualStudioProfessional and Enterprise, suitable for large teams and enterprises, providing additional features.

Using Visual Studio: Developing Software Across PlatformsUsing Visual Studio: Developing Software Across PlatformsApr 17, 2025 am 12:13 AM

Cross-platform development with VisualStudio is feasible, and by supporting frameworks like .NETCore and Xamarin, developers can write code at once and run on multiple operating systems. 1) Create .NETCore projects and use their cross-platform capabilities, 2) Use Xamarin for mobile application development, 3) Use asynchronous programming and code reuse to optimize performance to ensure efficient operation and maintainability of applications.

How to format json with vscodeHow to format json with vscodeApr 16, 2025 am 07:54 AM

The ways to format JSON in VS Code are: 1. Use shortcut keys (Windows/Linux: Ctrl Shift I; macOS: Cmd Shift I); 2. Go through the menu ("Edit" > "Format Document"); 3. Install JSON formatter extensions (such as Prettier); 4. Format manually (use shortcut keys to indent/extract blocks or add braces and semicolons); 5. Use external tools (such as JSONLint and JSON Formatter).

How to compile vscodeHow to compile vscodeApr 16, 2025 am 07:51 AM

Compiling code in VSCode is divided into 5 steps: Install the C extension; create the "main.cpp" file in the project folder; configure the compiler (such as MinGW); compile the code with the shortcut key ("Ctrl Shift B") or the "Build" button; run the compiled program with the shortcut key ("F5") or the "Run" button.

How to install vscodeHow to install vscodeApr 16, 2025 am 07:48 AM

To install Visual Studio Code, please follow the following steps: Visit the official website https://code.visualstudio.com/; download the installer according to the operating system; run the installer; accept the license agreement and select the installation path; VSCode will start automatically after the installation is completed.

How to enlarge fonts with vscodeHow to enlarge fonts with vscodeApr 16, 2025 am 07:45 AM

The methods to enlarge fonts in Visual Studio Code are: open the settings panel (Ctrl, or Cmd,). Search and adjust "Font Size". Choose "Font Family" with the right size. Install or select a theme that provides the right size. Use keyboard shortcuts (Ctrl or Cmd) to enlarge the font.

How to connect to a remote server with vscodeHow to connect to a remote server with vscodeApr 16, 2025 am 07:42 AM

How to connect to a remote server through VSCode? Install Remote - SSH Extended Configuration SSH Create a Connection in VSCode Enter connection information: Host, Username, Port, SSH Key Double-click the saved connection in Remote Explorer

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use