admin管理员组

文章数量:1332994

In a snippets extension, for a snippet, I need to set an import statement based on the file path.

Essentially the logic should be:

if ($RELATIVE_FILEPATH.startsWith('/app') {
    // Next.js with app router / RSC
    render 'import {...} from 'react-bricks/rsc'
} else {
    render 'import {...} from 'react-bricks/frontend'
}

Is it possible to have such a conditional?

Thank you!
Matteo

In a snippets extension, for a snippet, I need to set an import statement based on the file path.

Essentially the logic should be:

if ($RELATIVE_FILEPATH.startsWith('/app') {
    // Next.js with app router / RSC
    render 'import {...} from 'react-bricks/rsc'
} else {
    render 'import {...} from 'react-bricks/frontend'
}

Is it possible to have such a conditional?

Thank you!
Matteo

Share Improve this question edited Nov 21, 2024 at 12:06 rioV8 28.9k4 gold badges42 silver badges61 bronze badges asked Nov 20, 2024 at 16:33 Matteo FranaMatteo Frana 5794 silver badges12 bronze badges 1
  • 1 Please see How to Ask. Your title should be a clear, specific question without tags. – isherwood Commented Nov 20, 2024 at 20:25
Add a comment  | 

1 Answer 1

Reset to default 1

You can do that kind of a conditional in vscode snippets. Try this snippet:

"conditional": {
  "prefix": "cf",
  "body": [
    "$RELATIVE_FILEPATH",                // just to check what this outputs
      "render 'import {...} from 'react-bricks\/${RELATIVE_FILEPATH/^(\\app).*/${1:?rsc:frontend}/}'"
  ]
}

^(\\app).* puts the \app into capture group 1 (if it exists).

${1:?rsc:frontend} means if there is a capture group 1, output rsc, else (iff no capture group 1) output frontend.

Note that vscode is probably returning the path separators as \ rather than /.

You don't want any part of the RELATIVE_FILEPATH in your output, so be sure to match it ALL with ^(\\app).* - you only need to inspect the beginnging which is in capture group 1.

本文标签: visual studio codeVSCode Snippets conditional import based on file pathStack Overflow