Reputation: 968
I've got an npm package with badly written, out of date typings. I've written my own typings and now I'm wondering if I can somehow exclude the original typings from the npm package. It's not a simple extension of interfaces, the originals are basically garbage at this point.
Using the exclude list in tsconfig.json does not work for this purpose of course, since it still loads files from node_modules even if you exclude that folder.
Upvotes: 37
Views: 13306
Reputation: 373
I would recommend using patch-package
(https://www.npmjs.com/package/patch-package) for this.
Here's the technical procedure:
index.d.ts
file located in node_modules/{library}/index.d.ts
.patch-package
by running npm i patch-package
.package.json
file, add the following script under the "scripts" section:"scripts": {
"postinstall": "patch-package"
}
npx patch-package package-name
This approach allows you to make specific modifications to a package's code and maintain those changes using patch-package
.
Upvotes: 1
Reputation: 3907
You can get the desired behavior with the paths option in the tsConfig It could look something like this:
{
"compilerOptions": {
...
"paths": {
"*": [
"src/*",
"declarations/*"
]
}
},
...
}
With this config typescript looks for modules in src (there should be all the app source) and also in declarations, in the declarations folder I usually place my extra needed declarations.
To override the typings of a node module there are two options:
place a folder named like the module inside the declarations folder, containing a file called index.d.ts for the typings
place a declaration file, named like the module, inside the declarations folder
As a working example you can take a look at this repo https://github.com/kaoDev/react-ts-sample
An important hint by Bernhard Koenig:
The order of the paths matters. I had to put the path with my overrides before the path with the original type definitions so my overrides get picked up first. – Bernhard Koenig
Upvotes: 29
Reputation: 10298
Create node_modules
folder under your src
, then put typings of module(s) you want to overwrite inside:
├── node_modules
│ └── ...
│
└── src
├── index.ts
├── ... your codes ...
│
└── node_modules
└── <module-to-be-overwritten>
└── index.d.ts
No need to modify compilerOptions
in tsconfig.json.
Read How TypeScript resolves modules section in https://www.typescriptlang.org/docs/handbook/module-resolution.html.
Upvotes: 30