Search code examples
angulartypescriptwebpackangular5ng-packagr

How to use secondary endpoints to create API for Angular library


Scenario:

I created a custom UI library using ng-packagr, exported custom components and some model classes.

Problem:

In main project, import statement works fine for exported components but it doesn't work for exported classes and webpack fails to compile giving error:

module not found error can't resolve my-custom-library/models

Library project code:

Model class: src/app/modules/my-custom-module/models/my-model.ts

export class MyModel {
  constructor() {
    // default values for props here
  }

  // ...props here
}

Index file: src/app/modules/my-custom-module/models/index.ts

export * from './my-model';
export * from './my-other-model';

Export file at root: models.ts

export * from './src/app/modules/my-custom-module/models/index';

ng-packagr file at root: public_api.ts

export * from './models';

export * from './src/app/modules/my-custom-module/my-custom-module.module';
export * from './src/app/modules/my-custom-module/components/index';

Main project code:

import {MyCustomModule} from 'my-custom-library'; // works
import {MyModel} from 'my-custom-library'; // works
import {MyModel} from 'my-custom-library/models'; // does not works

Purpose: Simplifying and dividing the UI library API for end developers.

I believe, I'm missing something about mapping webpack module resolution because VS Code recognizes the import, intellisense works and even Ctrl + Click navigates to right file but webpack fails in compilation.

Git Issue


Solution

  • I was able to achieve my required API pattern using Seconday End Points.

    Credits: Alan Agius at Git Issue