Search code examples
angularangular-cliweb-componentangular-elements

Package Angular into Library


I've searched around and haven't quite figured out how to do this yet.
I have an Angular library I've created that contains custom components. This is being exported as Web Components so other applications outside of Angular can use them. However, in order for this to work, the Angular Core library needs to be included (among other angular libs).

How can I compile my library into a single file that contains everything needed to render my web components?


Solution

  • Although, you can bundle the angular dependency application into the final bundle of your library, that's considered a bad practice in general (of course, there are exceptions). The right approach to declare dependencies as external using dependency field of package.json file of your library.

    You can make use of module bundlers like Rollup or Webpack to achieve this. For, Rollup, you must use the the external configuration property. All the third-party module should be excluded. For Webpack, you use externals along with helper like webpack-node-externals.

    The reason to do this is to give the consumer of your library the freedom to provide dependencies in its own ways. For example, the dependent application may have its own angular copy and you risk double bundling the same library twice. And we are not just talking about that same library. It goes all way to transitive dependencies (dependencies of dependencies). Second, reason is that application may use bundler or global variables via CDN script to provide dependencies. Because of these reasons, as a library author, you should never make assumption about how users should consume your library. Even if you are the only one using that library, it is still good to have this clean approach/seggregation of the responsibilities.

    On a side note, you can use both Rollup and Webpack to bundle your libraries but historically and even today, Rollup has been a better choice for bundling libraries due to the clean ESM output it generates. Keep Webpack for application bundling.