I have an Angular library that contains a number of standalone components. Some of these components are dependent on third party libraries (angular2-draggable, @fortawesome/angular-fontawesome, etc.). My goal is that I can use this library in an application but only add dependencies for the components that are actually used in the application.
For example, the library has components of
In the consuming application, if I am only using component Foo, then I don't want to have a dependency on angular2-draggable. How can I do this?
It seems like the correct approach is to add angular2-draggable as an optional peer dependency, as in:
"sideEffects": false,
"peerDependencies": {
"angular2-draggable": "^16.0.0"
},
"peerDependenciesMeta": {
"angular2-draggable": {
"optional": true
}
}
The library will build and publish just fine. Everything installs as expected in the consuming application. But when starting the app, I'm getting errors like:
Error: Module not found: Error: Can't resolve 'angular2-draggable'
This is true even if Bar is not used at all in the consuming application. How can I ensure that only dependencies that are needed are required?
Optional dependencies only really work if you have multiple entry points in your library.
If you library has a barrel file with Foo and Bar, it will indeed fail like you saw it.
The solution for you would be to have a separate lib entry point for Bar