Regex, VS Code and Vue: Converting filename from CamelCase to kebab-case for a user snippet

I’ve been doing a lot of work using Vue.js to create CRUD SPAs linked to a Google Firebase backend. For the Vue (SFC) <template> components, I give the encapsulating  <div>  a class corresponding to the component filename, which is always a two-part descriptive name. Similar to the deprecated <style scoped> attribute, this makes it straightforward to contain styling to the component in question, rather than risking the contamination of the whole SPA, by prefixing styling with the encapsulating class name. For example:

<div class="edit-record">
  <h2>Edit Record</h2>
</div>

<style>
  .edit-record h2 {
    color: red;
  }
</style>

The component filename is always in CamelCase and the class name is always written in kebab-case (so, for instance, the file AddItem.vue would give the class name add-item”). However, doing this manually every time I create a new SFC is a waste of effort and runs the risk that I may forget to do it!

I use VS Code as my editor of choice. It provides the option of adding user-defined code snippets to boost productivity. I’ve defined a <template> snippet to add boilerplate when starting a new SFC. I wanted to automate the addition of the class name but I couldn’t find an example online for how to convert CamelCase to kebab-case. So, I wrote my own Regex to handle the conversion. I’m posting it for other developers who encounter the same issue.

The Regex is:

${TM_FILENAME_BASE/([A-Z][a-z]*)+([A-Z][a-z]*)/${1:/downcase}-${2:/downcase}/g}
Obviously, if you are using more than two elements to form you filename, the regex will need to be modified to reflect this.

Full boilerplate code

For interest, my current <template> boilerplate in the VS Code vue.json file is:
{
  "Vue Template": {
    "prefix": "template",
    "body": [
      "<template>",
      // Create div with class of kebab cased version of filename and "container"
      "  <div class='${TM_FILENAME_BASE/([A-Z][a-z]*)+([A-Z][a-z]*)/${1:/downcase}-${2:/downcase}/g} container'>",
      "",
      "  </div>",
      "</template>",
      "",
      "<script>",
      "  export default {",
      "    name: '$TM_FILENAME_BASE',",
      "    data() {",
      "      return {",
      "",
      "      }",
      "    }",
      "  }",
      "</script>",
      "",
      "<style>",
      "",
      "</style>"
    ],
    "description": "Vue SFC component template"
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top