preamble
“Series first appeared on Public"Non-homogeneous front-end journal. If you don't want to miss out on more exciting content, please "star" it and stay tuned to the public for the latest news.
Today we're going to talk about VS Code'sCustom Code Snippets。
This thing is justA godsend to improve coding efficiency, which, when used properly, can make it easier for you to knock out code!
Whether you're a newbie or a seasoned veteran, this guide will get you up and running in the world of code snippets.
Buckle up, we're taking off!
What the hell is a code snippet?
Simply put.Code snippets are pre-defined code templates. All you need to do is hit a few letters, and presto, a big piece of code pops up.
For example, you can set up a commonly used function structure as a code snippet, and the next time you need it, you can just type a shorttrigger word, generating an entire function framework in an instant.
Why do you need this?
save time:: No more annoying sample code to repeat. fewer mistakes: Pre-defined code snippets can avoid some low-level errors. hold together: Teams can share a common set of code snippets to ensure a consistent code style. increase efficiency: Generate complex code structures quickly, allowing you to focus on real logic implementation.
How do you make a whole code snippet of your own?
Here, follow me step by step.
Open VS Code and press Ctrl+Shift+P
(On a Mac, it'sCmd+Shift+P
)。importation" snippets
", SelectionPreferences: Configure User Snippets。Select the language in which you want to create the clip, e.g. JavaScript
。VS Code opens a JSON
file, which is your code snippet configuration file.
Here's an example.
{
"Console log": {
"prefix": "clog",
"body": ["('$1');", "$2"],
"description": "Print log to console."
}
}
Here."Console log"
It's the name of the clip."prefix"
It's a trigger word."body"
is the actual code content, the"description"
It's the description.
advanced skill
All right.We got the basics covered.。
Now for something more advanced!
1. Placeholders and tabs
placeholderare one of the most basic and powerful features of code snippets. Not only do they allow you to insert snippets after theQuickly jump to a specific location, and many more tricks can be realized.
Basic placeholders:
$1
,$2
,$3
etc.: These are the simplest placeholders. After inserting a clip, the cursor will first stop at the$1
position, pressTab
key and then jumps to the$2
And so on.$0
: This is the last tab. No matter how many placeholders you define.$0
It's always the end of the line.
Here's an example.
"Basic Function": {
"prefix": "func",
"body": [
"function ${1:functionName}(${2:params}) {",
"\t$0",
"}"
],
"description": "Create a basic function"
}
Default values in placeholders.
You can provide default values in placeholders in the form of${1:defaultValue}
。
"Console Log": {
"prefix": "clog",
"body": "('${1: Hello, world!) ;",
"description": "Print log with default values"
}
Options in placeholders.
You can also provide multiple options in the placeholder for the user to choose from. The format is${1|option1,option2,option3|}
。
"Variable Declaration": {
"prefix": "vard",
"body": "${1|const,let,var|} ${2:variable name} = ${3:value};",
"description": "Declare variables, optionally const/let/var."
}
2. Variables
VS Code
A number of built-in variables are provided that can be used in code snippets. These variables are replaced by their actual values when the snippet is inserted.
Commonly used built-in variables.
$TM_FILENAME
: The filename of the current file$TM_FILENAME_BASE
: The filename of the current file (without extension)$TM_DIRECTORY
: The directory where the current file is located$TM_FILEPATH
: Full file path of the current file$CLIPBOARD
: The contents of the current clipboard$WORKSPACE_NAME
: Name of the open workspace
Date and time variables.
$CURRENT_YEAR
:: Current year$CURRENT_MONTH
:: Current month (two-digit format)$CURRENT_DATE
:: Current date (two-digit format)$CURRENT_HOUR
: Current hour (24-hour system)$CURRENT_MINUTE
:: Current minute$CURRENT_SECOND
: Current seconds
A practical example.
"File Header": {
"prefix": "header",
"body": [
"/**",
" * Filename: $TM_FILENAME ",
" * Creation time: $CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND",
" * Author: ${1:$TM_USERNAME}",
" * Description: ${2: write file description here}",
" */"
],
"description": "Insert header comments"
}
Results of use:
/**
* :: File name.
* Created: 2023-08-29 15:30:00
* :: Author: YourUsername
* :: Description: Write the file description here
*/
3. Conversion
You can also perform all sorts of fancy operations on the values of variables and placeholders. These conversions can change the case, formatting, etc. of text.
Case Conversion.
${VAR/(.*)/${1:/upcase}}
: Convert to uppercase${VAR/(.*)/${1:/downcase}}
: Convert to lowercase${VAR/(.*)/${1:/pascalcase}}
) is converted to Pascal's nomenclature (PascalCase
)${VAR/(.*)/${1:/camelcase}}
) is converted to hump nomenclature (camelCase
)
A practical example.
"React Component": {
"prefix": "rcomp",
"body": [
"import React from 'react';",
"",
"const ${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/} = () => {",
"\treturn (",
"\t\t<div>",
"\t\t\t$0",
"\t\t</div>",
"\t);",
"};",
"",
"export default ${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/};"
],
"description": "Create React components that automatically use filenames as component names"
}
Results of use:
import React from 'react';
const App = () => {
return <div>$0</div>;
};
export default App;
This example automatically converts the filename toPascalCase
"Perfectly in line with theReact
Component naming convention.
4. Nested placeholders
You can stuff another placeholder inside a placeholder, which is called a nested placeholder. This allows you to create more complex interactive code snippets.
Here's an example.
"Conditional Statement": {
"prefix": "ifelse",
"body": [
"if (${1:condition}) {",
"\t${2:// code when condition holds}",
"} else {",
"\t${2/^(.*)$/$1/}",
"}"
],
"description": "Create if-else statements that automatically copy comments from the if block to the else block."
}
Results of use:
if (condition) {
// Code when the condition holds
} else {
// Code when the condition holds
}
In this example, whatever you type in the second placeholder is automatically copied into the else block. Pretty smart, huh?
Useful Code Snippet Examples
all talk and no actionCome and see the practical application!
React Hooks
Component.
"React Hooks Component": {
"prefix": "rhc",
"body": [
"import React, { useState, useEffect } from 'react';",
"",
"const ${1:ComponentName} = () => {",
"\tconst [${2:state}, set${2/(.*)/${1:/capitalize}/}] = useState(${3:initialState});",
"",
"\tuseEffect(() => {",
"\t\t$0",
"\t}, []);",
"",
"\treturn (",
"\t\t<div>",
"\t\t\t{${2:state}}",
"\t\t</div>",
"\t);",
"};",
"",
"export default ${1:ComponentName};"
],
"description": "Create a React component with useState and useEffect"
}
Results of use
import React, { useState, useEffect } from 'react';
const ComponentName = () => {
const [state, setState] = useState(initialState);
useEffect(() => {}, []);
return <div>{state}</div>;
};
export default ComponentName;
asynchronous function
:
"Async Function": {
"prefix": "afn",
"body": [
"async function ${1:functionName}(${2:params}) {",
"\ttry {",
"\t\tconst result = await ${3:asyncOperation};",
"\t\treturn result;",
"\t} catch (error) {",
"\t\('Error in ${1:functionName}:', error);",
"\t\tthrow error;",
"\t}",
"}"
],
"description": "Create an asynchronous function with error handling"
}
tip
Come up with a good name.: Give your code snippets memorable names and prefixes. For example, I like to use "rcomp" for React components.
Frequently updated: As your coding habits change, remember to update your code snippets. Regularly review your code snippet library.
Don't be greedy.Code snippets are great, but don't make everything a snippet. Only create snippets for really repetitive, complex code.
Learning from the Big Guy.
GitHub
There are a lot of great people sharing their code snippets on the site, so you can go and learn from them. Sometimes you'll find some awesome ideas!version control: Add your code snippet files to version control. I keep my snippets in a Git repository so I don't lose them when I change computers.
Regular cleaning:: Clean up your code snippets from time to time. Delete the ones you don't use anymore and update the ones that need improvement. Keep your snippet library organized.
summarize
Remember, the power of code snippets is that they make your codingFaster, more accurate, more consistent.
But, likeAll tools are the same. It's all about how you use them.。
Don't be afraid to try and experiment to find what works best for you.。
As you become more familiar with code snippets, you'll find your productivity increases dramatically.
You'll have more time and energy to focus on solving real problems instead of getting bogged down in tedious details.
Don't forget that sharing is the ladder of progress。
If you've created some awesome code snippets, share them with your coworkers or the larger developer community.
All right.vscode The code snippet has been taught, now it's up to you.
Remember that.Practice makes perfect.
wish you luck! (when signing off on a correspondence)Coding
Have fun, productivity is flying! ✨🚀
Thanks for reading and we'll see you next time!