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
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

How to run vue with vscodeHow to run vue with vscodeApr 16, 2025 am 07:39 AM

Running a Vue project in VSCode requires the following steps: 1. Install the Vue CLI; 2. Create a Vue project; 3. Switch to the project directory; 4. Install project dependencies; 5. Run the development server; 6. Open the browser to visit http://localhost:8080.

How to compare two files with vscodeHow to compare two files with vscodeApr 16, 2025 am 07:36 AM

How to compare files in VSCode: 1. Open two files, 2. Enable the Differences view (View menu), 3. View the Differences (Add green, delete red, modify purple), 4. Use the arrow keys to navigate, 5. Accept or reject changes. Additional features include merging changes, copying changes, viewing details, and editing differences.

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment