I've written a library published to a private npm repo which is used by my applications.
This library contains utilities and has dependencies to other libraries, as an example let's choose @aws-sdk/client-lambda
.
Some of my applications use only some of the utilities and don't need the dependencies to the external libraries, while some applications use all of the utilities.
To avoid having all applications getting a lot of indirect dependencies they don't need, I tried declaring the dependencies as peerDependencies
and having the applications resolve the ones they need. It works well to publish the package, and to use it from applications who declare all of the peerDependencies
as their own local dependencies
, but applications failing to declare one of the dependencies get build errors when the included .d.ts
files of the library are imported in application code:
error TS2307: Cannot find module '@aws-sdk/client-kms' or its corresponding type declarations.
Is it possible to resolve this situation so that my library can contain many different utils but the applications may "cherry-pick" the dependencies they need to fulfill the requirements of those utilities in runtime? Do I have to use dynamic imports to do this or is there another way?
I tried using @ts-ignore
in the library code, and it was propagated to the d.ts
file imported by the applications, but it did not help.
Setup:
my-library
package.json:
peerDependencies: {
"@aws-sdk/client-lambda": "^3.27.0"
}
foo.ts:
import {Lambda} from '@aws-sdk/client-lambda';
export function foo(lambda: Lambda): void {
...
}
bar.ts:
export function bar(): void {
...
}
index.ts:
export * from './foo';
export * from './bar';
my-application1 - works fine
package.json:
dependencies: {
"my-library": "1.0.0",
"@aws-sdk/client-lambda": "^3.27.0"
}
test.ts:
import {foo} from 'my-library';
foo();
my-application2 - does not compile
package.json:
dependencies: {
"my-library": ...
}
test:ts:
import {bar} from 'my-library';
bar();