vscode 中用户自定义代码片段很简单.
如上图, 点击文件 - 首选项 - 用户代码片段, 点击新建代码片段:
弹出对话框, 输入你想要的代码片段的名称, 如 test, 就来到了编辑界面:
其中标红部分是一个完整的示例, 取消注释, 即能达到输入 log 字符, 按 tab 键将输出: console.log('光标') 的效果, 并且再按 tab 键, 可以到达下一行.
这里我们建一个 vue 的 html 模板代码片段, 如下:
- {
- // 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": "html",
- "prefix": "vuehtml",
- "body": [
- "<!DOCTYPE html>",
- "<html lang=\"en\">",
- "<head>",
- "<meta charset=\"UTF-8\">",
- "<meta name=\"viewport\"content=\"width=device-width, initial-scale=1.0\">",
- "<meta http-equiv=\"X-UA-Compatible\"content=\"ie=edge\">",
- "<title>$0</title>",
- "<script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"></script>",
- "</head>",
- "<body>",
- "","<script>","",
- "</script>",
- "</body>",
- "</html>"
- ],
- "description": "a vue html template"
- }
- }
当在 vscode 中新建一个 HTML 后缀文件, 在文件中输入 vuehtml 按 tab, 即可实现以下输出:
- <!DOCTYPE HTML>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8″>
- <meta name=" viewport " content="width=device-width, initial-scale=1.0″>
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>
- </title>
- <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">
- </script>
- </head>
- <body>
- <script>
- </script>
- </body>
- </HTML>
参考资料:
Snippets in Visual Studio Code
来源: http://www.mzh.ren/vscode-user-defined-snippets.html