VsCode - Triggering a snippet upon file creation
Asked Answered
I

1

9

I wanted to know if it is possible to trigger a user defined custom snippet when I create a file in vscode.

I started learning Golang recently and noticed that there is some boilerplate code that goes into creating the main.go file.

So I created my custom snippet for it and now now I can trigger the snippet manually and save me some keystrokes of typing.

I wanted to go one step further, so that whenever I create a new file named main.go from within VsCode, it should automatically fire that snippet and insert the biolerplate code for me, without me having to manually trigger the snippet.

Is this even possible ?

Illustration answered 10/4, 2019 at 13:55 Comment(4)
How are you creating the new file? That would be helpful info as there is more than one way to do so.Danyluk
I am creating the file from within the vscode using the menu options in explorer.Illustration
You could easily do this by writing a simple VSCode extension.Orlene
Only if I knew how to write a "simple" extension, I wouldn't have asked on SO.!!Illustration
D
8

Check out this extension: Auto Snippet:

With this in your settings.json:

"autoSnippet.snippets": [
  { "pattern": "**/main.go", "snippet": "main-go-template" },
],

[Note that the example settings in the extension docs has a few syntax errors - use my example above - I have filed an issue with the creator.]

And then your snippet

"main-go-template": {
  "prefix": "zz",
  "body": [
    ...  // you can use tabstops and transforms just like regular snippets
  ]
  "description": "javascript template"
}

Then creating a new main.go file or opening an empty one should trigger the snippet.

It is a good idea to reload vscode whenever you make a change to this extension's settings.

Here is a demo of a gulpfile with common boilerplate:

demo of auto snippet extension


Also see this extension https://marketplace.visualstudio.com/items?itemName=bam.vscode-file-templates

Danyluk answered 19/10, 2019 at 4:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.