14

I am new to angular,

started writing my first library, containing components, services, directives.

i listed my components, services, directives in the library's exports array, but still:

  • When using the library form another library or application, and to compile successfully, i needed to list my components and services in the public-api.ts. why ? isn't the ngModule's exports array enough?

  • now deleted the components,services, directives from the exports array and everything still works. why ?

reading around the docs at angular.io, it looks like public-api.ts and exports serve the same purpose - i am probably missing something basic here.

0

2 Answers 2

13

The exports of a @NgModule defines what is exposed to other modules when that module is imported in the imports of another module. The public-api acts as a barrel file for cleaner path imports.

Example:

// Instead of this
import { ExampleService } from '@lib/services/example.service';
import { AntoherService } from '@lib/sevivces/another.service';

// You can do this
import { ExampleService, AnotherService } from '@lib';

https://angular.io/api/core/NgModule#exports https://basarat.gitbook.io/typescript/main-1/barrel

1
  • Does public_api.ts just a convention, but this still doesn't stop users from importing something inside the Angular library? Sep 28, 2021 at 23:43
7

exports in ngModule act as Angular part of export, and public-api.ts export typescript symbol of your component/pipe/directive.

The second export is not required but recommended to keep your import path clean.

with public-api.ts (recommended)

import {A, B, C} from 'my-library'

without public-api.ts

import {A} from 'my-library/a'
import {B} from 'my-library/b'
import {C} from 'my-library/c'

inside your my-module.module.ts (works well but not as smart as public-api.ts)

import {A, B, C} from 'my-library/my-module'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.