I created a custom snippet in Visual Studio Code(inside a .code-snippets file I created from Code>Preferences>Configure User Snippets) for a boilerplate react functional component. In this snippet I want to extract relative filepath and filename of current file I'm in when I use the snippet in that file. I want to place the file path and file name at the very top. Say I create a file(MyComponent.js) for a functional component and it is located in folder: src/components/. When I enter this snippet into the file I will get "// src/components/MyComponent.js" at the very top. I found a solution from another post but I had to tweak it a little to get my intended results. I don't know much about regular expressions and I wanted to know if anyone can confirm that the code I used is indeed sufficient and if i can get an explanation on what the code actually does. This is the code in question:

${RELATIVE_FILEPATH/^([^\\/\\\\]+[\\/\\\\])|(\\.ex|\\.exs)$|([^._\\/\\\\]+)|_|([\\/\\\\])/$3$4/g}

This is the snippet that is generated in MyComponent.js:

// src/components/MyComponent.js  
// ====================================================  
import React from 'react'  
export default function MyComponent() {  
    return (
        <div>
  
        </div>  
    )  
}

This is code behind that snippet inside .code-snippets file in ~/Library/Application Support/Code/User/snippets/:

    "boilerplatereact": {  
      "scope": "javascript,typescript",  
      "prefix": "boilerplatereact",  
      "body": [  
        "// ${RELATIVE_FILEPATH/^([^\\/\\\\]+[\\/\\\\])|(\\.ex|\\.exs)$|([^._\\/\\\\]+)|_|([\\/\\\\])/$3$4/g}",  
        "// ====================================================",  
        "import React from \''react\''",  
        "export default function $TM_FILENAME_BASE() {",  
        "\treturn (",  
        "\t\t<div>",  
        "\t\t\t${TM_SELECTED_TEXT}$1",  
        "\t\t</div>",  
        "\t)",  
        "}"  
        ],  
      "description": "boilerplate for react functional component"  
    }  

I found a solution from another post(titled: VS Code snippet regex for relative path). I tweaked it to get my intended results. I'm still not certain how it works or if it is the correct way in vscode. I need confirmation.

0

There are 0 best solutions below