如何在代码片段(Snippet)中实现驼峰命名转大写下划线自动生成?
Absolutely! This is totally achievable with almost all modern code editors that support snippet variables and transform functions—VS Code is the most widely used example, so I’ll focus on that first, plus note how other editors handle it too.
Is This Feasible?
100% yes. The key here is leveraging your editor’s ability to reference snippet variables and apply regex-based transformations (or built-in conversion functions) to auto-generate the uppercase snake_case version from your camelCase input.
Step-by-Step Implementation (VS Code)
Here’s exactly how to build a snippet that does this:
Open your user snippets: Press
Ctrl+Shift+P(Windows/Linux) orCmd+Shift+P(Mac), typePreferences: Configure User Snippets, then choose either a language-specific snippet file (likejavascript.jsonfor JS/TS) or create a global snippet file (e.g.,global.code-snippets).Add the snippet definition: Paste this JSON into the file (you can tweak the prefix and body to match your needs):
{ "Auto-convert camelCase to UPPER_SNAKE_CASE Action": { "prefix": "action-camel-to-snake", "body": [ "export function ${1:setVisibilityFilter}(payload) {", " return {", " type: '${2:${1/(.)([A-Z])/$1_$2/g/upcase}}',", " payload", " };", "}" ], "description": "Creates a function with auto-generated uppercase snake_case type from camelCase name" } }
How the transformation works:
${1:setVisibilityFilter}: This is your input variable—type any camelCase text here (e.g.,updateUserSettings).${2:${1/(.)([A-Z])/$1_$2/g/upcase}}: This references the first variable, applies two transformations:- The regex
(.)([A-Z])finds every lowercase letter followed by an uppercase letter, replacing them with$1_$2(adding an underscore between them). - The
/upcaseflag converts the entire transformed string to uppercase.
- The regex
- So
updateUserSettingsautomatically becomesUPDATE_USER_SETTINGS.
Use the snippet: Type the prefix
action-camel-to-snakein your editor, hitTab, then type your camelCase function name. When you pressTabagain to move to thetypefield, the uppercase snake_case version will already be there—no manual typing needed!
For Other Editors
- Sublime Text: Use regex replacements in your snippets. The logic is similar—reference the input variable and apply a regex to insert underscores before uppercase letters, then convert to uppercase.
- WebStorm/IntelliJ IDEA: Use Live Templates. You can define a variable with the
camelCaseToConstant()built-in function, which does exactly this conversion out of the box.
This trick saves tons of repetitive typing and ensures consistency between your function names and corresponding constant types.
内容的提问来源于stack exchange,提问作者lukaszpolowczyk

