Introduction

Before Angular 6, there is no out of box tooling support to build a Library, and it is a complex task. In Angular 6, Angular CLI provide a option of generating Library using ng-packagr, the new option make building Library a much more easier task.

But sharing Library between multiple apps is still an area that lack of best practice and standard structure.

The most direct option is to publish the library into npm, and reference it from there. But in a typical corporate environment, the source code is required to be in private repository. This article will show how to setup and release a library into a private repository, and share it between multiple Apps within a team.

Build a Angular 6 Library

Just a quick overview for the process of build a Library.

Create a new workspace project Generate a new Library Build the Library

Result

Library Project Structure

Share the Library

To share the Library between multiple Apps, what is really need to be shared is the Distribution Package (in the Dist folder of the Project structure image). So we want to publish and expose the Distribution as a separated repo while still keep it within the original parent repo structure.

To achieve that, git subtree is used as illustrated in the diagram below.

Here we have two repos, demong6lib as parent repo containing source, and demong6lib-dist as subtree repo containing distribution packages.

To create the dist folder as subtree, firstly add a new dist repo (it can be empty) git subtree add — prefix=dist/demo-ng6lib <URL for new dist repo> master Then rebuild the library, this will create a number of files in dist folder. Use git add and git commit to commit all the new files. After the above steps are setup correctly, we can update subtree repo with parent repo by git subtree push. git subtree push — prefix=dist/demo-ng6lib <URL for new dist repo> master

You can find the demo repos here:

Consume the Library

The newly setup library can be consumed just as a normal npm package as below in package.json file:

“demo-ng6lib”: “git+https://[URL for new dist repo]”

Versioning

To control the version, you can add a git hashtag behind the url

Enjoy the journey!