angularangular-clicode-sharing

Sharing code between Angular applications


I have an existing Durandal app that are actual two apps tangled into each other.

I want to rewrite the app(s) in Angular and want to distinct app's sharing common code.

I have estimated that around 80% of the code can bee shared.

I would like to use the angular-cli if that's possible. But I am really looking for best practice on how to share code between Angular apps.


Solution

  • Take a look at Minko's blog post on creating Angular Libraries. This is because you will want to create the 80% of your reusable code as one or many sharable internal libraries. You can then publish these to an internal NPM repository.

    Then you can simply use angular-cli for creating the apps which consume these libs.

    There are two important points that Minko talks about in the blog linked above. These are being sure your libs are compatible with Angular's AoT and that they are tree-shakable.

    UPDATE 2-Nov-20202

    Another option is to to use the monorepo pattern where you would have your libraries and applications in the same repository, making code reuse easier.

    Monorepo and microrepo both have advantages and disadvantages. Either pattern will require buy-in from the organisation and tooling for CICD and/or dependancy management.

    If you are considering monorepo, look into the Nrwl Nx tooling.