乐闻世界logo
搜索文章和话题

How to create and use VS Code snippets?

2月18日 18:25

VS Code Snippets and Custom Templates

VS Code snippets are reusable code templates that can be quickly inserted via shortcuts to insert common code patterns, significantly improving coding efficiency.

Snippet Files

Snippets are stored in .vscode/*.code-snippets files, or globally in the user directory.

Creating Snippets

  1. Through menu: File > Preferences > User Snippets
  2. Select a language or create global snippets
  3. Edit the JSON format snippet file

Snippet Syntax

Basic Structure

json
{ "Snippet Name": { "prefix": "trigger", "body": [ "code line 1", "code line 2" ], "description": "Snippet description" } }

Tabstops

Use $1, $2, etc. to define cursor positions:

json
{ "Function Template": { "prefix": "func", "body": [ "function ${1:functionName}(${2:parameters}) {", "\t$0", "}" ], "description": "Create a function" } }

Choice Tabstops

Provide multiple options to choose from:

json
{ "Console Log": { "prefix": "log", "body": [ "console.${1|log,warn,error|}($2);" ], "description": "Console log statement" } }

Variables

Use predefined variables:

json
{ "File Header": { "prefix": "header", "body": [ "// File: ${TM_FILENAME}", "// Author: ${TM_USERNAME}", "// Date: ${CURRENT_YEAR}-${CURRENT_MONTH}-${CURRENT_DATE}" ], "description": "File header comment" } }

Common Variables

  • TM_FILENAME: Current file name
  • TM_FILENAME_BASE: File name without extension
  • TM_DIRECTORY: Current file directory
  • TM_FILEPATH: Full path of current file
  • CLIPBOARD: Clipboard content
  • CURRENT_YEAR: Current year
  • CURRENT_MONTH: Current month
  • CURRENT_DATE: Current date

Language-specific Snippets

JavaScript/TypeScript

json
{ "React Component": { "prefix": "react-component", "body": [ "import React from 'react';", "", "interface ${1:ComponentName}Props {", "\t${2:prop}: ${3:type};", "}", "", "const ${1:ComponentName}: React.FC<${1:ComponentName}Props> = ({ ${2:prop} }) => {", "\treturn (", "\t\t<div>", "\t\t\t${4:content}", "\t\t</div>", "\t);", "};", "", "export default ${1:ComponentName};" ], "description": "React functional component with TypeScript" } }

Python

json
{ "Python Class": { "prefix": "class", "body": [ "class ${1:ClassName}:", "\t\"\"\"${2:Class description}\"\"\"", "\t", "\tdef __init__(self${3:, args}):", "\t\t${4:pass}" ], "description": "Python class template" } }

HTML

json
{ "HTML5 Boilerplate": { "prefix": "html5", "body": [ "<!DOCTYPE html>", "<html lang=\"en\">", "<head>", "\t<meta charset=\"UTF-8\">", "\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">", "\t<title>${1:Page Title}</title>", "</head>", "<body>", "\t${2:content}", "</body>", "</html>" ], "description": "HTML5 boilerplate" } }

Advanced Features

Transforms

Transform variables:

json
{ "Import Statement": { "prefix": "import", "body": [ "import { ${1:${TM_FILENAME_BASE/(.*)/${1:/capitalize}/}} } from './${1}';" ], "description": "Import statement with capitalized name" } }

Nested Snippets

Call other snippets within a snippet.

Global Snippets

Create snippets that work for all languages, file named global.code-snippets:

json
{ "TODO Comment": { "prefix": "todo", "body": [ "// TODO: ${1:description} - ${CURRENT_YEAR}-${CURRENT_MONTH}-${CURRENT_DATE}" ], "description": "TODO comment with date" } }

Usage Tips

  1. Trigger: Type prefix and press Tab
  2. Navigate Tabstops: Press Tab to move between placeholders
  3. Multi-cursor Editing: Use same tabstop number for multi-cursor editing
  4. Snippet Priority: Project snippets > Global snippets

Important Notes

  • Snippet files use UTF-8 encoding
  • Avoid using overly long prefixes
  • Provide clear descriptions
  • Test snippets in different scenarios
  • Consider team collaboration, share useful snippets
标签:VSCode