vsCode之代码用户片段

498 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第3天

工欲善其事必先利其器

vsCode之代码用户片段

痛点:很多代码每天写好多好多遍,比如forEach,console.log(),箭头函数等等

解决方法:配置代码用户片段

下面是我配置之后的操作

html文件,输入<!出现右边的代码片段,按回车自动生成代码,光标会自动聚焦到title的位置,输完title按回车光标去到script的src引号处(有没有很方便)

再来看看js,输入csl出现右边的代码片段,按回车自动生成代码,光标自动聚焦到括号中

配置方法:

  • vsCode左下方——>设置——>配置用户代码片段

  • 配置html文件快捷键搜索html,配置js文件快捷键搜索JavaScript,配置less文件快捷键搜索less,以此类推,我配置了下面这些

  • json文件配置方式,打开一个新的配置json文件,上面会有描述和例子

下面给一个例子,html.json

{
	// Place your snippets for html here. Each snippet is defined under a snippet name and has a prefix, body and 
	// description. 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": {
	// 	"prefix": "log",
	// 	"body": [
	// 		"console.log('$1');",
	// 		"$2"
	// 	],
	// 	"description": "Log output to console"
	// }
    "<!":{
        "prefix": "<!",
        "body":[
            "<!DOCTYPE html>",
            "<html>",
            "        <head>",
            "            <meta name="renderer" content="webkit">",
            "            <meta charset="utf-8">",
            "            <meta name="viewport" content="width=device-width,initial-scale=1.0">",
            "            <title>$1</title>",
            "        </head>",
            "        <body>",
            "            <div id="app"></div>",
            "            <script src="$2"></script>",
            "        </body>",
            "</html>"
        ],
        "description": "html"
    }
}

几个注意的点

  1. body中的字符串之间用逗号分隔
  2. 引号里面加空格才有作用,在引号外面加是没有用的

配置了几个常用的js代码片段

{
	"csl":{
        "prefix": "csl",
        "body":[
            "console.log($1)"
        ],
        "description": "console.log"
    },
    "df":{
        "prefix": "df",
        "body": [
            "()=>{",
            "    $1",
            "}",
        ],
        "description": "箭头函数"
    },
    "fe":{
        "prefix": "fe",
        "body": [
            ".forEach(item =>{",
            "    $1",
            "})"
        ]
    },
    "fori":{
        "prefix": "fori",
        "body": [
            "for(let key in arr){",
            "    $1",
            "}"
        ],
        "description": "循环对象"
    },
    "for1":{
        "prefix": "for1",
        "body": [
            "for(let i=0;i<xxx.length;i++){",
            "    $1",
            "}"
        ],
        "description": "循环数组"
    }
}

中文输入法下输入英文标点符号

痛点:在写代码的时候,是不是经常敲中文(注释之类的),完了再敲小括号大括号都需要切换输入法;在输入法中勾选上“中文时使用英文标点”完美解决

默认输入法也有这个功能

开启之后是不是担心想输中文标点的时候怎么办呢?放心,按ctrl+句号就可以输入中文标点了