search
HomeDevelopment ToolsVSCodeLearn about snippets in VSCode and see how to improve development efficiency!

如何把vscode snippets用在项目中提高开发效率?下面本篇文章带大家了解一下vscode中的snippets,介绍一下使用它提高项目开发效率的方法,希望对大家有所帮助!

Learn about snippets in VSCode and see how to improve development efficiency!

code snippets 是代码片段的意思,是 vscode 提供的根据某字符串快速补全一段代码的功能,可以提高写代码的效率。【推荐学习:《vscode教程》】

Learn about snippets in VSCode and see how to improve development efficiency!

vscode 的 snippets 是可以随项目共享的,多人开发一个项目的时候,可以维护项目级别的 snippets 并且通过 git 共享,来提高项目开发效率。

下面我们来详细了解下 snippets。

snippets 的功能

snippets 配置的格式如下:

{
  "For Loop": {
    "prefix": ["for", "for-const"],
    "body": ["for (const ${2:element} of ${1:array}) {", "\t$0", "}"],
    "description": "A for loop."
  }
}
  • prefix 是触发 snippets 的前缀,可以通过数组指定多个
  • body 是填入到编辑器的内容
  • description 是 snippets 的描述

其中 body 部分可以通过 ${} 的方式指定光标位置、顺序、占位字符串、可用的值等,有 5 种语法,我们分别来看一下:

光标跳转:1 1 2

可以通过 11、2 指定光标位置,当填入 snippets 的内容之后,光标会设置到 1的位置来编辑,当编辑完,可以通过tab来跳到1 的位置来编辑,当编辑完,可以通过 tab 来跳到2。

比如这段配置:

{
 "测试": {
  "scope": "javascript,typescript",
  "prefix": "test",
  "body": [
   "$1  xxxx",
   "yyyy $2",
  ],
  "description": "光标跳转"
 }
}

效果为:

Learn about snippets in VSCode and see how to improve development efficiency!

还有当有多个 11、2 等,编辑一处其他内容也会同步修改,也就是 vscode 的多光标编辑。

比如:

{
 "测试": {
  "scope": "javascript,typescript",
  "prefix": "test",
  "body": [
   "$1  xxxx $1",
  ],
  "description": "多光标"
 }
}

效果为:

Learn about snippets in VSCode and see how to improve development efficiency!

通过这种功能可以快速编辑 snippets 中的可编辑内容。

占位符:${1: placeholder}

只是光标跳转虽然可以快速编辑内容,但是不知道编辑的部分是什么,所以 snippets 支持了设置 placeholder 的值,默认会选中该段文本,输入内容即可覆盖。

比如:

{
 "测试": {
  "scope": "javascript,typescript",
  "prefix": "test",
  "body": [
   "${1:aaa}  xxxx",
   "yyyy ${2:bbb}",
  ],
  "description": "光标跳转"
 }
}

效果为:

Learn about snippets in VSCode and see how to improve development efficiency!

可选值:${1|text1,text2,text3|}

占位符的方式就像 input 标签加了个 placeholder 属性,还是要手动输入,当可编辑区域是有几个可选的值的话,就要换成下拉选择,在 snippets 里就是通过 ${1|text1,text2,text3|} 的方式支持,在 | 和 | 之间填入通过 , 分割的多个选项。

比如:

{
 "测试": {
  "scope": "javascript,typescript",
  "prefix": "test",
  "body": [
  "${1|神说要有光,卡颂|}"
  ],
  "description": "可选值"
 }
}

效果为:

Learn about snippets in VSCode and see how to improve development efficiency!

变量:$变量名

在模版可编辑位置填入内容的时候,有的时候需要用到选中的值、剪贴板的值、文件名、日期等,这些信息通过 snippets 中支持的变量来取。

比如:

  • TM_FILENAME: 文件名
  • TM_CURRENT_LINE: 当前行的内容
  • CLIPBOARD: 剪贴板内容
  • WORKSPACE_NAME:workspace 的名字
  • WORKSPACE_PATH:workspace 的路径
  • CURRENT_YEAR:当前年
  • CURRENT_MONTH:当前月
  • CURRENT_DATE:当前日
  • RANDOM: 随机数
  • RANDOM_HEX: 6 位随机 16 进制数
  • UUID: 唯一 id

可以取这些变量的值来填入到光标位置,方式就是使用 TM_FILENAMETM\_FILENAME、CURRENT_YEAR 的方式。

比如:

{
 "测试": {
  "scope": "javascript,typescript",
  "prefix": "test",
  "body": [
  "当前文件: $TM_FILENAME",
  "当前日期: $CURRENT_YEAR/$CURRENT_MONTH/$CURRENT_DATE"
  ],
  "description": "变量"
 }
}

效果为:

Learn about snippets in VSCode and see how to improve development efficiency!

变量转换:${变量名/匹配的正则/替换到的字符串/匹配模式}

支持了变量的填入还不行,因为有的变量的内容不合适,需要做一些字符串替换,所以 snippets 支持了 transform 的功能。

比如 abc-123.js 的文件,

我们通过 $TM_FILENAME 取到文件名,然后把后缀去掉转成大写填入

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

对文件名 TM_FILENAME 做正则匹配 (.*).[a-z]+,把分组一变成大写之后返回,匹配模式为忽略大小写(ignore)。

{
    "填入文件名": {
            "scope": "javascript,typescript",
            "prefix": "filename",
            "body": [
                    "${TM_FILENAME/(.*)\\.[a-z]+/${1:/upcase}/i}"
            ],
            "description": "文件名"
    }
}

我们实验下效果:

Learn about snippets in VSCode and see how to improve development efficiency!

可以看到,正确的取到了文件名,并且去掉后缀转成大写填入了。

知道了 snippets 的功能,那么怎么设置 snippets 呢?snippets 在什么范围内生效呢?

snippets 的范围

command + shift + p 打开命令面板,输入 snippet,选择 configure user snippets:

Learn about snippets in VSCode and see how to improve development efficiency!

可以选择创建全局的、项目范围的、语言范围的 snippets:

Learn about snippets in VSCode and see how to improve development efficiency!

分别会打开不同位置的文件来添加 snippets。

语言级别的 snippets 是对于特定语言才生效,这个还可以封装成插件。在插件的 package.json 中配置下即可:

{
  "contributes": {
    "snippets": [
      {
        "language": "javascript",
        "path": "./snippets.json"
      }
    ]
  }
}

项目范围的 snippets 是在项目根目录的 .vscode/xxx.code-snippets 下面添加的,vscode 启动的时候会读取这些文件,然后使之在项目范围内生效。

当有一些项目级别的代码片段可以共享的时候,完全把这个文件提交到远程 git 仓库,然后项目成员都可以共享这些 snippets 设置。对于一些模版代码比较多的项目,还是比较有意义的。

总结

snippets 是 vscode 提供的用于提高开发效率的一些快速输入代码片段的功能,支持光标位置的跳转、多光标同时编辑、占位符、可选值、变量、变量转换等功能,灵活运用这些功能,可以作出易用的提高开发效率的 snippets。

snippets 有 global、language、project 3 种生效范围:global 是全局的设置;language 是语言级别的设置,可以进一步封装成插件共享;project 则是项目范围内的,在 .vscode 下的 xx.code-snippets 中,完全可以提交到 git 仓库,和其他成员共享。

灵活运用 snippets 功能,是可以提高开发效率的,而且这个也是可以项目级别共享的。希望这篇文章能够帮大家了解 snippets。

原文地址:https://juejin.cn/post/7005878164517814280

作者:zxg_神说要有光

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Learn about snippets in VSCode and see how to improve development efficiency!. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金--zxg_神说要有光. If there is any infringement, please contact admin@php.cn delete
Visual Studio: Exploring the Free and Paid OfferingsVisual Studio: Exploring the Free and Paid OfferingsApr 22, 2025 am 12:09 AM

The main difference between the free and paid versions of VisualStudio is the richness of features and the service supported. The free version (Community) is suitable for individual developers and small teams, providing basic development tools; the paid version (Professional and Enterprise) provides advanced features such as advanced debugging and team collaboration tools, suitable for large projects and enterprise-level development.

Visual Studio Community Edition: The Free Option ExplainedVisual Studio Community Edition: The Free Option ExplainedApr 21, 2025 am 12:09 AM

VisualStudioCommunityEdition is a free IDE suitable for individual developers, small teams and educational institutions. 1) It provides functions such as code editing, debugging, testing and version control. 2) Based on the Roslyn compiler platform, it supports multiple programming languages ​​and integrates Git and TFVC. 3) Advanced features include unit testing, optimization suggestions include turning off unnecessary extensions and using a lightweight editor.

Visual Studio: Building Applications with EaseVisual Studio: Building Applications with EaseApr 20, 2025 am 12:09 AM

VisualStudio is an integrated development environment (IDE) developed by Microsoft, which supports a variety of programming languages, including C#, C, Python, etc. 1. It provides IntelliSense function to help write code quickly. 2. The debugger allows setting breakpoints, step-by-step code execution, and identifying problems. 3. For beginners, creating a simple console application is a great way to get started. 4. Advanced usage includes the application of design patterns such as project management and dependency injection. 5. Common errors can be solved step by step through debugging tools. 6. Performance optimization and best practices include code optimization, version control, code quality inspection and automated testing.

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.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor