2

I am trying to create a simple snippet that allows me to create JS Constructors. So far, what I have is

"class constructor": {
    "prefix": "class",
    "body": [
        "class ${1:ClassName} {",
            "\t\tconstructor({${2:thisName}: ${2}}) {",
                "\t\t\tthis.${2} = ${2}",
            "\t}",
        "}"
    ],
    "description": "class constructor template"
},

This works as expected, but what I am trying to see if it is possible to add multiple entries which also creates a new line for this, but in this case, the snippet runs its course once I fill in the details for $2{thisName}. What I am hoping for is the ability to add multiple key value pairs.

So instead of it ending at:

class ClassName {
  constructor({ thisName:  thisName}) {
    this. thisName =  thisName
  }
}

I would like to be able to add other items so that it looks like; where a new line for this.another = another is created automatically.

class ClassName {
  constructor({ thisName:  thisName, another: another}) {
    this. thisName = thisName
    this.another = another // this is create
 }

}

The ${3}.. doesn't work here because there could be any amount of items.

1 Answer 1

4

Try this:

"class constructor": {
  "prefix": "class",
  "body": [

    "class ${1:ClassName} {",
          "\t\tconstructor({${2/([^,]+)([,\\s]*|)/$1: $1${2:+, }/g}}) {",
          "${2/([^,]+)([,\\s]*|)/\t\t\tthis.$1 = $1${2:+\n}/g}",
          "\t}",
      "}"
  ],
  "description": "class constructor template"
},

snippet with multiple call arguments

See my answer at Make a vscode snippet that can use a variable number of arguments for more explanation.

You can use any number of arguments in a snippet as long as you capture them in the same regex capture group - here each arg is in capture group $1.

Then each one is replaced! In your case by \t\t\tthis.$1 = $1${2:+\n the second time. After the tabs, the capture group is used in this.$1 = $1

Then capture group 2 is inspected ${2:+\n}. It either has the , or nothing. If it has something, add a \n, otherwise nothing will be added.

For this regex to work you should enter your args as

arg1, arg2, arg3, arg4

-- with comma separators (withor without spaces after the commas). After your last argument hit tab to fire the snippet transform.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.