2

I have created a simple package that contains an index.d.ts at the root. Here is the content:

declare var foo: number;

I have then created a separate project which adds that package using npm link. In Visual Studio Code, foo is not getting picked up. I have also tried adding "types": "./index.d.ts" to the package.json where index.d.ts resides. It is not working. In my playground project, I have the following tsconfig.json:

{
  "compilerOptions": {
    "target": "es2018",
    "module": "esnext",
    "jsx": "preserve",
    "strict": false,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "resolveJsonModule": true
  }
}

Why is the index.d.ts not getting picked up by Visual Studio Code in the project?

1 Answer 1

2

I don't know, how your library package will be included, so first some common rules:

If you import the package as module, index.d.ts at package root (or with package.json entry) will be picked up automatically via module resolution.

If package types are just global type declarations (nothing to import from a module), TS would find it automatically in node_modules/@types of any enclosing folder, see typeRoots configuration.

So, let's say you just have declare var foo: number; in the file (it is then a global declaration file) and types are under node_modules/my-lib, not node_modules/@types/my-lib, then you would need to manually tell TS to include it in the compilation.

Easiest way is probably to add it to the files property of tsconfig.json, which specifies additional files to be included explicitely. See the good example section in the docs. An alternative would be to adjust typeRoots, but that is probably overkill here.

My guess is there is a second error cause: npm link will create a symlink and per default TS uses those paths, the symlinks resolve to (the real paths).

We can fix that by enabling --preserveSymlinks option (tsc --preserveSymlinks) to use location of the symbolic link file instead (see also compiler options). What docs say to this option:

In this mode, references to modules and packages (e.g. imports and /// directives) are all resolved relative to the location of the symbolic link file, rather than relative to the path that the symbolic link resolves to.

Sign up to request clarification or add additional context in comments.

1 Comment

I love you! Worked like a charm without preserveSymlink :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.