Search code examples
typescriptvisual-studio-codeintellisense

Add path to search classes in intellisense


I'm working on a TypeScript project in Visual Studio Code and I want Intellisense to search for classes and give me tips not only in my project folder but also in another folder.

This is my folder structure:

├───@lib
│   └───typescript
│       └───src
│           └───logger.ts
│
└───typescript
    └───myproject
            main.ts
            myproject.code-workspace
            package.json
            tsconfig.json

The project I'm working on is on typescript/myproject folder.

While editing typescript/myproject/main.ts, I want to import Logger class from ../../@lib/typescript/src/logger. This works fine if I manually type the path, but I want to type Logg in the editor and be able to use Intellisense to auto import Logger class from the desidered path, like if the class was in the same project or in any subfolder.

I already tried to create a workspace (myproject.code-workspace) with both folders (myproject and typescript, or typescript/src).

I also tried to edit typescript/myproject/tsconfig.json adding path to "include" like below, but nothing happens:

{
    "compilerOptions": {
        ....
    },
    "include": [
        "../../@lib/typescript",
        "../../@lib/typescript/src"
    ]
}

How to tell intellisense to search classes and methods from ../../@lib/typescript/src path?


Solution

  • The problem here is that you are referencing code from outside of your project. You are be able to import code from outside of the rootDir of typescript by writing the whole direction because the only validation that we have there is that the path exists. Even if this works in runtime and compile time, I would suggest to kill two birds with one stone by defining external dependencies as they are:

    // typescript/myproject/package.json
      "dependencies": {
        "@lib": "../../@lib"
      }
    
    

    Very important for this to work is to make @lib a package. This means that where you are pointing in your path should contain a valid package.json with a main property, pointing to the modules that the package is exporting. For example, only if @lib/typescript is not a package, you could do something like this:

    // @lib/package.json
      "main": "./typescript/src/logger.ts" // Or even better, point to an index.ts with all the exports.
    
    

    After making thins change, you need to run npm install inside typescript/myproject in order to create a symlink between your folder and its representation in node_modules.

    Now, you will have intellisense working with the new imports available in your project, by reference the new module as the name you used, @lib in this case:

    import { Logger } from '@lib';
    

    This also allows you to not need to refactor the entire project just because the path changed.