在vscode中用户可以通过自定义代码模板和设置自定义代码快捷键。在前端开发领域,一些好的自定义代码能够加快我们的开发进度,提升开发效率。下面推荐一些常用的自定义代码片段。
设置自定义代码文件(snippets)
通过vscode个人设置的Snippets选项选择或者创建一个自定义snippets文件。
snippets的文件格式类似JSON,文件中key的含义如下:
prefix:设置自定义代码对应的快捷键。
body:自定义代码片段主体,为数组形式,具体可参考后续代码。
description:对该段自定义代码片段的描述。
推荐自定义代码片段
let:通过自定义let代码可以更加方便的定义变量。
// ${2:key为占位符,默认为key,输入完后按Tab跳转到value处。"let": {"prefix": "let", //自定义快捷键"body": ["let ${2:key} = ${3:value};"],"description": "let声明变量"},
实际效果:
logs:在实际开发过程中,console.log是常用的调试方法之一,通过自定义代码片段能够快速的生成调试代码
//$1 $1 为两个同名占位符,触发自定义代码段后两个占位符同时出现光标"logs": { "prefix": "logs", "body": [ "console.log('!!!这是$1', $1);" ], "description": "控制台打印变量"},
实际效果:
logg:或者采取下列方法,复制想要打印的变量名,随后logg触发自定义代码片段即可。!!!强烈推荐
//$CLIPBOARD$1能够自动识别剪切板的内容,强烈推荐!!!"paste to log": {"prefix": "logg","body": ["console.log('!!!这是$CLIPBOARD$1', $CLIPBOARD$1);"],"description": "打印出剪切板内容"},
实际效果:
vue3:设置该快捷键可以一键生成vue文件的基础框架
"vue3": {"prefix": "vue3","body": ["<template>"," <div>","$1"," </div>","</template>\n","<script lang=\"ts\" setup>","import { ref } from \"vue\" ","$2","</script>\n","<style lang=\"less\" scoped>","$3","</style>"],"description": "vue3"},
实际效果:
完整代码
为了方便铁铁们的使用和调试,因此贴出完整代码,如下所示(好使的话点个赞和收藏吧,球球了):
{"vue3": {"prefix": "vue3","body": ["<template>"," <div>","$1"," </div>","</template>\n","<script lang=\"ts\" setup>","import { ref } from \"vue\" ","$2","</script>\n","<style lang=\"less\" scoped>","$3","</style>"],"description": "vue3"},"logs": {"prefix": "logs","body": ["console.log('!!!这是$1', $1);"],"description": "控制台打印变量"},"let": {"prefix": "let","body": ["let ${2:key} = ${3:value};"],"description": "let声明变量"},"paste to log": {"prefix": "logg","body": ["console.log('!!!这是$CLIPBOARD$1', $CLIPBOARD$1);"],"description": "打印出剪切板内容"},}