angularangular-libraryng-packagr

Migrate Angular functions to common library


Our Angular project has evolved to have a bunch of functions that don't really belong in any class (in addition to all the normal classes of course). We now need a new Angular project that wants to also use some of these functions. These are all private and will never be in a public repo

I've made a new project and am using it but all the imports look like

import { func1 } from "common-library"

i.e. there's no concept of a namespace here.

How do I structure this such that I end up with something like

import { func1 } from "common-library/functionset1"
import { func1 } from "common-library/functionset2"

And ditto for the classes. I want to to avoid the possibly of a class with a generic name like Item causing a conflict in the future


Solution

  • You can achieve this with secondary entry points. To create one, make sure to follow this folder structure:

    common-library
    ├── src
    |   ├── public_api.ts
    |   └── *.ts
    ├── ng-package.json
    ├── package.json
    └── functionset1
        ├── src
        |   ├── public_api.ts
        |   └── *.ts
        └── ng-package.json
    └── functionset2
        ├── src
        |   ├── public_api.ts
        |   └── *.ts
        └── ng-package.json
    

    The content of the ng-package.json file inside functionset1 and functionset2 can be simply {}.

    Also make sure that your common-library/src/public_api.ts file exports something, even if you don't have anything to export. Otherwise there will be a build error, see this GitHub issue. For example:

    export const emptyPackage = true;