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