wessberg / rollup-plugin-ts

A TypeScript Rollup plugin that bundles declarations, respects Browserslists, and enables seamless integration with transpilers such as babel and swc
MIT License
495 stars 33 forks source link

Seemingly no support typeRoots to provide typings for 3rd party packages #122

Open flying-sheep opened 3 years ago

flying-sheep commented 3 years ago

Reproduction

I provide typings for some untyped modules using typeRoots in tsconfig.json. In my case I created typings/react-did-catch/index.d.ts and imported it.

Example repo here: https://github.com/flying-sheep/rollup-plugin-ts-test

Expected Behavior

rollup-plugin-ts compiles my code.

Actual Behavior

index.tsx → index.js...
[!] (plugin Typescript) TS6504: File '~/Dev/.../node_modules/react-did-catch/lib/index.js' is a JavaScript file. Did you mean to enable the 'allowJs' option?

Uh, no, I do not, that’s why I provided typings!

clemyan commented 3 years ago

Just ran into a similar problem. I have done some investigation and determined both issues have the same root cause.

A little background: typeRoots are effectively implemented by implicitly adding a type reference directive (/// <reference type="x" />) to a project. (e.g. if you install @types/node, TypeScript effectively adds /// <reference type="node" /> to your project since node_modules/@types/ is a type root and it can find node_modules/@types/node)

Those references are resolved by calling resolveTypeReferenceDirectives. TypeScript's default implementation (used by tsc) is to lookup the typeRoots directories for a matching .d.ts file or a package with declared typings in package.json, then fallback to a normal resolution to package.

However, this plugin redirects those lookups directly to the normal resolution. This causes it to ignore typeRoots.

At best, the normal resolution actually falls back to trying @types/${moduleName} if moduleName is not found (this is how this plugin can still find @types/node while ignoring typeRoots). At worst a project has both moduleName and a type root for it and it resolves to the wrong path. For your case, TypeScript found a type root at typings and included a react-did-catch directive to your project, but when TypeScript tries to resolve that to a d.ts file, this plugin ignores typeRoots and resolves to node_modules/react-did-catch/lib/index.js instead of /typings/react-did-catch/index.d.ts.

I can maybe try to make a PR later this week.