DEV Community

Cover image for VSCode Custom Snippets: Powerful Feature That Boosts Your Productivity (Advanced)
Jesse Wei
Jesse Wei

Posted on

VSCode Custom Snippets: Powerful Feature That Boosts Your Productivity (Advanced)

In Part1 of this series, we learned,

  • What snippets are in VSCode and why we need them.
  • How to create simple snippets
  • How to create more advanced snippets with multiple lines and placeholders.

In part 2, we will learn about placeholder transform and create a more sophisticated snippet using it.

Placeholder Transform

Sometimes when we replaced a placeholder with the target value, we want to make changes to it before inserting it to our code. For example, in React.js, it's a convention to use the useState hook like this,

const [name, setName] = useState("");
Enter fullscreen mode Exit fullscreen mode

The state variable (name) and the noun part of its updater function (Name) are normally the same except the latter is capitalized.

If we create a snippet like we did before, we get setname rather than the desired setName.

"My useState": {
  "prefix": "us",
  "body": "const [${1:state}, set${1:state}] = useState($0)",
  "description": "My useState snippet"
},
Enter fullscreen mode Exit fullscreen mode

name substring in setname is not capitalized

This is where placeholder transform comes in handy. In the example above, if we define the snippet like the following instead, we can get the desired result.

"My useState": {
  "prefix": "us",
  "body": "const [${1:state}, set${1/(.*)/${1:/capitalize}/}] = useState($0)",
  "description": "My useState snippet"
}
Enter fullscreen mode Exit fullscreen mode

There's a lot going on here.

  • First, we define a tab stop $1 with a placeholder value state.
  • We want $1 to be used in the set part as well, only that the value of $1 should be capitalized.
  • So we perform a transformation by matching the whole string of $1 (string state) using a regular expression (.*).
  • Then we reference the first capture group (here is the whole matched string state) and capitalize it with ${1:/capitalize}.

setname becomes setName

Variable Transform

VScode snippets also support variable transform. It works just like placeholder transform and shares the same syntax as placeholder transform with the only difference being the target to be transformed is a variable instead of a placeholder.

The variables can be used, however, are pre-defined so the use cases of variables are somewhat limited. But you may find yourself use it at certain point in your development.

For more information about variable transform, see VSCode's official documentation.

Takeaways

In part 2, we learned,

  • When and how to use placeholder transform.
  • Similar to placeholder transform is variable transform with limited pre-defined variables that can be used.

Top comments (0)