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