TypeScript: TypeScript paths are not resolved in definition files

TypeScript Versions: 3.5.3 and 3.7.0-dev.20190820

Search Terms: typescript paths remain after compile in type definition files

Code

index.ts

export * from '~/b'

b.ts

export const myThing = 'Something'

tsconfig.json

{
  "compilerOptions": {
    "target": "esnext",
    "module": "es2015",
    "declaration": true,
    "outDir": "dist",
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": "./",
    "paths": {
      "~/*": ["src/*"]
    }
  }
}

Expected behavior:

/dist/index.d.ts

export * from './b'

Actual behavior:

/dist/index.d.ts

export * from '~/b'

More Info:

My package.json has

{
    "main": "dist/index.js",
     "types": "dist/index.d.ts",
}

When someone imports the package, the types are broken because the paths don’t resolve to the expected files.

Perhaps I am approaching this incorrectly. Is there an alternative method to deal with path resolution?

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 17 (2 by maintainers)

Most upvoted comments

Thumb up if you used baseUrl, rootDirs and now you are here 😃

This is the intended behavior. TypeScript’s golden rule about import paths is never change what the user wrote; this applies both to .d.ts and .js outputs. This is the most predictable behavior and the most controllable from the dev side.

How you want to fix this really depends on why you wrote it as ~/b in the first place.

paths is for when you have module paths that are already resolvable at runtime, but TS doesn’t understand them, so you can point the compiler to where it can find them.

It’s not an aliasing feature, sadly.

This issue has been marked ‘Working as Intended’ and has seen no recent activity. It has been automatically closed for house-keeping purposes.

How you want to fix this really depends on why you wrote it as ~/b in the first place.

A nice default I use for projects is set ~ as the src directory, allowing for the use of absolute imports.

import env from ~/environment`

vs

import env from '../../../environment'

When using absolute paths in a library which is intended to be hosted in npm, the absolute paths no longer register as the application is compiled into a different folder.

Should I set my tsconfig.compilerOptions.path to { "~/*": ["./src/*", "./dist/*" ]

For the record, your use case–sometimes wanting to use a rooted path instead of multiple levels of ../–is why I support the path form @/absolute/path at runtime in miniSphere. I wish it were possible to do the same in Node.js (rooted at the location of package.json, for example) but unfortunately it isn’t 🙁

Oh. So what is the intended use case for paths?

You shouldn’t use paths at all in that case - paths exists to instruct the compiler how the runtime is expected to interpret paths, not to dictate to TS how to rewrite them so they work at runtime.