赶快把常用的代码都做成代码片段snippets吧,它真的很香!

7,445 阅读2分钟

一、什么是代码片段?

效率与质量是开发者永远追求的目标,组件化、工具化、工程化我们一直不停息的探索着。对于代码片段可能关注的人没那么多。我理解的代码片段是开发或者团队使用频率高、模板化的代码段,最通俗的解释就是经常复制粘贴的代码。

你可能觉得这完全可以通过抽离公共库来解决,但是有些是公共库不好解决的,比如下面的组件是我们自己的组件库的组件,使用的场景是非常的多的,那能不能每次用的时候不手敲或者复制粘贴呢?代码片段snippets就可以帮助我们解决。

image.png

把它抽成代码片段llsUploadFile

llsUploadFile.gif

是不是感觉瞬间效率了很多,对那些比较长的代码片段,会给我们带来更多的效率提升。

那接下来我们看下如何用代码片段?

二、如何用代码片段?

  • 新建代码片段,我建的是全局代码片段

llsTest.gif

我们看到代码片段可以按照全局和局部,也可以按照语言来分类,我一般都会做成全局的代码片段。

  • 使用代码片段

llsTestYanshi.gif

三、代码片段语法

我们先看下示例代码

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

  • 首先代码片段是个json对象

  • 都有一个key作为描述,比如

    "Print to console": {

    }
  • 可以通过scope指定语言,不指定的所有语言都生效
"Print to console": {
    "scope": "javascript,typescript",
 }
  • prefix是触发的前缀,可以指定多个
"Print to console": {
    "scope": "javascript,typescript",
    "prefix": ["log", "console"]
 }
  • body 是插入到编辑器中的内容
"Print to console": {
    "scope": "javascript,typescript",
    "prefix": ["log", "console"],
    "body": [
            "console.log();"
    ],
 }
  • description是描述
"Print to console": {
    "scope": "javascript,typescript",
    "prefix": ["log", "console"],
    "body": [
            "console.log();",
    ],
    "description": "Log output to console"
 }
  • $1$2等用来指定光标的位置, 并且可以指定多个光标位置,通过tab切换光标位置
    "Print to console": {
            "scope": "javascript,typescript",
            "prefix": "log",
            "body": [
                    "console.log('$1');",
                    "$2"
            ],
            "description": "Log output to console"
    }

llsTestYanshi.gif

  • placeholder加光标位置默认值
    "Print to console": {
            "scope": "javascript,typescript",
            "prefix": "log",
            "body": [
                    "console.log('$1:Hello');",
                    "$2"
            ],
            "description": "Log output to console"
    }

llsTestYanshi2.gif

如果掌握了以上规则的基本上可以满足工作场景的90%以上需求,代码片段snippets还可以使用正则等,如果有需要可以搜索学习下,其实使用都非常的简单。

赶快把你常用的代码段抽成代码片段snippets吧,相信会对你的开发效率有一定帮助的~