2

I'd like to create a VS-Code snippet for importing css into a react component. If I'm using the snippet in "MyComponent.tsx", then I'd like the snippet to import the associated css file for the component:

import "./MyComponent.css";

The component and it's css will always be located in the same directory.

I thought that the following snippet would be able to do this:

//typescriptreact.json
      "import componet css": {
        "prefix": "icss2",
        "body": [
          "import \"./${1:$TM_FILENAME/^(.+)(\.[^ .]+)?$/}.css\";"
        ],
        "description": ""
      },

But this results in:

import "./MyComponent.tsx/^(.+)([^ .]+)?$/.css";

What's the correct way to do this?

2 Answers 2

2

You can use

"import componet css": {
    "prefix": "icss2",
    "body": [
      "import \"./${TM_FILENAME_BASE/^(.*)\\..*/$1/}.css\";"
    ],
    "description": ""
}

The ${TM_FILENAME_BASE} variable holds the file name without the path, and the ^(.*)\\..* regex matches and captures all up to the last . while just matching the extension, and only the captured part remains due to the $1 replacement pattern (that refers to Group 1 value).

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

Comments

0
"import component css": {
    "prefix": "icss2",
    "body": [
        "import \"./${TM_FILENAME_BASE}.css\";"
    ],
    "description": ""
}

TM_FILENAME_BASE The filename of the current document without its extensions

from snippet variables documentation.

So there is no need to remove the .tsx extension via a transform - it is already done for you.


The more interesting question is what if you have a file like

myComponent.next.tsx // what should the final result be?

${TM_FILENAME_BASE} will only take off the final .tsx resulting in import "./myComponent.next.css";

@Wiktor's results in import "./myComponent.css";

Which is correct in your case? Is something like myComponent.next.tsx a possible case for you? If not just use ${TM_FILENAME_BASE} with no need for a transform.

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.