1

I'm trying to create a TypeScript snippet in Visual Studio Code which includes a bunch of import statements, but I want the path to be set dynamically depending on which directory you use the snippet.

For example, I have a snippet like this:


import { MyComponent } from "../../ui/components";
import { isString } from "../../../../utils/string";

export const Foo = (props) => {
    const isStr = isString(props.foo);
    /* ...More code... */
    return <MyComponent></MyComponent>;
};

How can I make sure that the import paths are set relative to the direcotry I execute the snippet? If this is not possible, are there any other ways you would recommend for achieving this?

CookieEater
  • 2,237
  • 3
  • 29
  • 54

1 Answers1

-1

Yes, you could. VScode has provided some built-in variables to get relative and full path of your working file.

The structure of my demo project looks like this:

├── index.html
├── style.css
└── test
    └── test.ts

And my import path snippet for typescript is:

{
    // Place your snippets for typescript here. Each snippet is defined under a snippet name and has a prefix, body and 
    // description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
    // $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the 
    // same ids are connected.
    // Example:
    "Import path": {
        "prefix": "impo",
        "body": [
            "import { $1 } from \"${2:$RELATIVE_FILEPATH}\";",
        ],
        "description": "Import path depending on relative file path"
    }
}

When I type impo in test/test.ts, the snippet expands like this:

enter image description here

If $RELATIVE_FILEPATH is not what you want, you can feel free to change to other variables listed in the documentation.

ramsay
  • 3,197
  • 2
  • 14
  • 13
  • But, this doesn't achieve what I want, does it? That just gives a relative path to the current file, but the file I want to import is somewhere else and it could be anywhere. Also, why would you import from "test/test.ts" when your file is test.ts?? Your example doesn't make sense or I misunderstood something. – CookieEater Jul 09 '22 at 15:53