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?

Mark
  • 143,421
  • 24
  • 428
  • 436
ANimator120
  • 2,556
  • 1
  • 20
  • 52

2 Answers2

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).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
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.

Mark
  • 143,421
  • 24
  • 428
  • 436