search
HomeDevelopment ToolsVSCodeHow to define code snippets in VSCode to make coding so fast!

VSCode中怎么定义代码片段?下面本篇文章给大家介绍一下给VSCode定义代码片段的方法,让coding速度快到飞起,希望对大家有所帮助!

How to define code snippets in VSCode to make coding so fast!

代码片段可以理解为模板,当我们输入指定时,按下【tab】或者【enter】即可出现对应的模板。【推荐学习:《vscode入门教程》】

只要代码片段写的好,升职加薪少不了~

代码片段的好处与坏处

coder对代码片段的评价褒贬不一,下面这张图解释了代码片段的好处与坏处:

How to define code snippets in VSCode to make coding so fast!

何时使用代码片段

关于什么时候使用代码片段,我的建议是:

  • 当你对一个东西足够熟练,例如console.log(),这个时候可以为其设置代码片段。
  • 有些东西特别繁琐,每次都需要写一遍,例如Vue单文件中的初步定义的内容。

当然,上面的内容仅仅是我的建议。

如何设置代码片段

首先你准备一个VSCode,然后确定你操作系统,然后开始操作:

  • Windows系统:【 文件】→【首选项】→【用户片段】
  • Mac系统: 【Code】→【首选项】→【用户片段】

然后你就可以看到下面这个内容

How to define code snippets in VSCode to make coding so fast!

然后你就可以对现有的代码片段进行修改,或者创建一个新的代码片段,这里我们创建一个名为test-snippets的全局代码片段,来进行演示。

代码片段语法

我们创建完成以后,会出现一个类似于JSON的语法,内容如下:

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

接下来我们对VSCode中的代码片段语法进行学习。

首先中的内容是被一个对象进行包裹,对象中的每一个属性表示一个代码片段,属性名为代码片段的名称,在触发代码片段的时候会展示匹配到的代码片段名称,例子中的属性名称为Print to console

接下来我们学习代码片段内每个属性是干什么的。

  • scope:表示代码片段作用于哪种语言。 不同语言之间以,隔开。 常用的有javascript, typescript,html,css,vue等。 如果设置为""就代表所有地方都生效。
  • prefix:对应触发代码片段的字符。
  • description:代码片段的描述。
  • body:对象代码片段的内容,通常为一个数组,数组内的一行对应生成代码片段后的一行。

推荐一个用于生成代码片段的网站,链接如下:https://snippet-generator.app/

$占位符

上面的例子中,我们输入log按下【tab】键即可出现如下代码:

console.log();

出现这段内容后,光标在()内,然后按下【tab】键,光标即可调到下一行,也就是$2的位置,同样的道理,我们还可以设置$3$4 等等

值得注意的是:$0用于设置最终光标的位置。

默认与可选项

如果想让占位符中具有一个默认值,可以通过${1:defalt}的形式来编写。

如果行提供一些选项,可以通过${1|one,two,three|}的形式来编写,例如:

{
  "import": {
    "scope": "javascript,typescript",
    "prefix": "import",
    "body": [
      "import { $2 } from \"${1|axios,lodash,day|}\"",
      "$3"
    ],
    "description": "导入模块"
  }
}

测试如下:

How to define code snippets in VSCode to make coding so fast!

然后按下【tab】后如下图

How to define code snippets in VSCode to make coding so fast!

常量

在代码片段中,VSCode为我们提供了一些常量,使用方式也比较简单,例如$TM_FILENAME

TM_SELECTED_TEXT       当前选定的文本或空字符串
TM_CURRENT_LINE        当前行的内容
TM_CURRENT_WORD        光标下的单词的内容或空字符串
TM_LINE_INDEX          基于零索引的行号
TM_LINE_NUMBER         基于一索引的行号
TM_FILENAME            当前文档的文件名
TM_FILENAME_BASE       当前文档的文件名(不含后缀名)
TM_DIRECTORY           当前文档的目录
TM_FILEPATH            当前文档的完整文件路径
CLIPBOARD              剪切板里的内容
WORKSPACE_NAME         已打开的工作空间或文件夹的名称

CURRENT_YEAR           当前年(四位数)
CURRENT_MONTH          当前月
CURRENT_DATE           当前日
CURRENT_DAY_NAME_SHORT 当天的短名称(’Mon’)
CURRENT_HOUR           当前小时
CURRENT_MINUTE         当前分钟
CURRENT_SECOND         当前秒

BLOCK_COMMENT_START   块注释开始标识,如 PHP /* 或 HTML <!--
BLOCK_COMMENT_END     块注释结束标识,如 PHP */ 或 HTML -->
LINE_COMMENT          行注释,如: PHP // 或 HTML <!-- -->

为项目创建代码片段

有些时候我们需要为具体的项目创建一些代码片段,其实也比较简单,我们只需要在当前项目的根目录创建一个.vscode文件夹,然后创建以.code-snippets的结尾的文件即可,写法与上面一致。

Written at the end

Here I created a GitHub repository and put some code snippets in VSCode. The repository address is as follows: https://github.com/ywanzhou/vscode-snippets

You’ve all seen this, why don’t you give it a like and support~

For more knowledge about VSCode, please visit: vscode tutorial! !

The above is the detailed content of How to define code snippets in VSCode to make coding so fast!. 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 Professional and Enterprise: Paid Versions and FeaturesVisual Studio Professional and Enterprise: Paid Versions and FeaturesMay 10, 2025 am 12:20 AM

The difference between VisualStudioProfessional and Enterprise is in the functionality and target user groups. The Professional version is suitable for professional developers and provides functions such as code analysis; the Enterprise version is for large teams and has added advanced tools such as test management.

Choosing Between Visual Studio and VS Code: The Right Tool for YouChoosing Between Visual Studio and VS Code: The Right Tool for YouMay 09, 2025 am 12:21 AM

VisualStudio is suitable for large projects, VSCode is suitable for projects of all sizes. 1. VisualStudio provides comprehensive IDE functions, supports multiple languages, integrated debugging and testing tools. 2.VSCode is a lightweight editor that supports multiple languages ​​through extension, has a simple interface and fast startup.

Visual Studio: A Powerful Tool for DevelopersVisual Studio: A Powerful Tool for DevelopersMay 08, 2025 am 12:19 AM

VisualStudio is a powerful IDE developed by Microsoft, supporting multiple programming languages ​​and platforms. Its core advantages include: 1. Intelligent code prompts and debugging functions, 2. Integrated development, debugging, testing and version control, 3. Extended functions through plug-ins, 4. Provide performance optimization and best practice tools to help developers improve efficiency and code quality.

Visual Studio vs. VS Code: Pricing, Licensing, and AvailabilityVisual Studio vs. VS Code: Pricing, Licensing, and AvailabilityMay 07, 2025 am 12:11 AM

The differences in pricing, licensing and availability of VisualStudio and VSCode are as follows: 1. Pricing: VSCode is completely free, while VisualStudio offers free community and paid enterprise versions. 2. License: VSCode uses a flexible MIT license, and the license of VisualStudio varies according to the version. 3. Usability: VSCode is supported across platforms, while VisualStudio performs best on Windows.

Visual Studio: From Code to ProductionVisual Studio: From Code to ProductionMay 06, 2025 am 12:10 AM

VisualStudio supports the entire process from code writing to production deployment. 1) Code writing: Provides intelligent code completion and reconstruction functions. 2) Debugging and testing: Integrate powerful debugging tools and unit testing framework. 3) Version control: seamlessly integrate with Git to simplify code management. 4) Deployment and Release: Supports multiple deployment options to simplify the application release process.

Visual Studio: A Look at the Licensing LandscapeVisual Studio: A Look at the Licensing LandscapeMay 05, 2025 am 12:17 AM

VisualStudio offers three license types: Community, Professional and Enterprise. The Community Edition is free, suitable for individual developers and small teams; the Professional Edition is annually subscribed, suitable for professional developers who need more functions; the Enterprise Edition is the highest price, suitable for large teams and enterprises. When selecting a license, project size, budget and teamwork needs should be considered.

The Ultimate Showdown: Visual Studio vs. VS CodeThe Ultimate Showdown: Visual Studio vs. VS CodeMay 04, 2025 am 12:01 AM

VisualStudio is suitable for large-scale project development, while VSCode is suitable for projects of all sizes. 1. VisualStudio provides comprehensive development tools, such as integrated debugger, version control and testing tools. 2.VSCode is known for its scalability, cross-platform and fast launch, and is suitable for fast editing and small project development.

Visual Studio vs. VS Code: Comparing the Two IDEsVisual Studio vs. VS Code: Comparing the Two IDEsMay 03, 2025 am 12:04 AM

VisualStudio is suitable for large projects and Windows development, while VSCode is suitable for cross-platform and small projects. 1. VisualStudio provides a full-featured IDE, supports .NET framework and powerful debugging tools. 2.VSCode is a lightweight editor that emphasizes flexibility and extensibility, and is suitable for various development scenarios.

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 Article

Hot Tools

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.

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.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor