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 vs. VS Code: Which is Better for Your Project?Visual Studio vs. VS Code: Which is Better for Your Project?Apr 14, 2025 am 12:03 AM

VisualStudio is suitable for large projects and development scenarios that require strong debugging capabilities, while VSCode is suitable for scenarios that require flexibility and cross-platform development. VisualStudio provides a comprehensive development environment, supports .NET development, and integrates debugging tools and project management functions. VSCode is known for its lightweight and extensibility. It supports multiple programming languages ​​and enhances functions through plug-in systems, and is suitable for modern development processes.

Visual Studio: Exploring Pricing and Licensing OptionsVisual Studio: Exploring Pricing and Licensing OptionsApr 13, 2025 am 12:03 AM

Visual Studio is available in three versions: Community Free Edition is for individuals and small teams, Professional Paid Edition is for professional developers and small and medium teams, and Enterprise Ultimate Edition is for large enterprises and complex projects.

Visual Studio's Value: Weighing the Cost Against Its BenefitsVisual Studio's Value: Weighing the Cost Against Its BenefitsApr 12, 2025 am 12:06 AM

VisualStudio is highly valuable in .NET development because it is powerful and comprehensive. Despite the high cost and resource consumption, the efficiency improvement and development experience it brings is significant. Community is ideal for individual developers and small teams; large enterprises are suitable for Professional or Enterprise.

Visual Studio's Availability: Which Editions Are Free?Visual Studio's Availability: Which Editions Are Free?Apr 10, 2025 am 09:44 AM

Free versions of VisualStudio include VisualStudioCommunity and VisualStudioCode. 1. VisualStudioCommunity is suitable for individual developers, open source projects and small teams. It is powerful and suitable for individual projects and learning programming. 2. VisualStudioCode is a lightweight code editor that supports multiple programming languages ​​and extensions. It has a fast startup speed and low resource usage, making it suitable for developers who need flexibility and scalability.

How to install Visual Studio for Windows 8?How to install Visual Studio for Windows 8?Apr 09, 2025 am 12:19 AM

The steps to install VisualStudio on Windows 8 are as follows: 1. Download the VisualStudioCommunity2019 installation package from the official Microsoft website. 2. Run the installer and select the required components. 3. It can be used after installation is completed. Be careful to select Windows 8-compatible components and make sure there is sufficient disk space and administrator rights.

Can my computer run VS Code?Can my computer run VS Code?Apr 08, 2025 am 12:16 AM

VSCode can run on most modern computers as long as the basic system requirements are met: 1. Operating system: Windows 7 and above, macOS 10.9 and above, Linux; 2. Processor: 1.6GHz or faster; 3. Memory: at least 2GB RAM (4GB or higher recommended); 4. Storage space: at least 200MB of available space. By optimizing settings and reducing extended usage, you can get a smooth user experience on low-configuration computers.

How do I make a program compatible with Windows 8?How do I make a program compatible with Windows 8?Apr 07, 2025 am 12:09 AM

To make the program run smoothly on Windows 8, the following steps are required: 1. Use compatibility mode, detect and enable this mode through code. 2. Adjust API calls and select the appropriate API according to the Windows version. 3. Perform performance optimization, try to avoid using compatibility mode, optimize API calls and use general controls.

Does VS Code work on Windows 8?Does VS Code work on Windows 8?Apr 06, 2025 am 12:13 AM

Yes,VSCodeiscompatiblewithWindows8.1)DownloadtheinstallerfromtheVSCodewebsiteandensurethelatest.NETFrameworkisinstalled.2)Installextensionsusingthecommandline,notingsomemayloadslower.3)Manageperformancebyclosingunnecessaryextensions,usinglightweightt

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

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