How can I create templates for file extensions in Visual Studio Code?

In my Vue.js projects almost all the times I need this code snippet as a template.

<template>
    <div>
    </div>
<template>

<script>

export default{
    data(){
        return{
        }
    },
    methods:{
    },
    created(){
    }
}
</script>

<style scoped>
</style>

Is there a way to tell Visual Studio Code each and every time I create a file with the extension .vue to automatically add that snippet to the file?

Simply, when I create new file with a certain extension, the predefined template for that extension should automatically be added to the file.


There isn't, not natively. But there is an extension called File Templates for VSCode that allows you to create your own file templates and generate from them. But I think you'd benefit from making an extension to do just that and maybe even more.

In the meantime, you can use a snippet to generate this instead of having to copy paste.

Go to File > Preferences > User Snippets and choose Vue from the dropdown. Vue will only show up if you have installed an extension that supports this file type. In this case, I'd recommend Vetur, but you probably have it already.

Then just add this entry to your vue.json file:

"vuetpl" : {
        "body": [
            "<template>",
            "\t<div>",
            "\t\t$0",
            "\t</div>",
            "</template>",

            "<script>",

            "export default{",
            "\tdata(){",
                "\t\treturn{",
                    "\t\t\t",
                "\t\t}",
            "\t},",
            "\tmethods:{",
                "\t\t",
            "\t},",
            "\tcreated(){",
                "\t\t",
            "\t}",
            "}",
            "</script>",

            "<style scoped>",
            "</style>",
        ],
        "prefix": "vuetpl",
        "description": "Creates a new template."
    }

Then, when you create a new .vue file, just type vuetpl and press tab to autocomplete, and you'll have this:

Template

Of course, you can also use a Snippet Generator to make your own snippets.


The extension Auto Snippet does exactly that.

You only need to configure two things:

  • The snippet's name
  • A filename pattern or a language for when the snippet should be applied

Recommendation

The author has some very custom defaults, so as soon as you install it, modify its settings and remove those patterns that you won't need.

Otherwise, it will complain every time you create a file and doesn't find the snippet configured.