Why do i need *public-api.ts* and also *exports*
Asked Answered
W

2

16

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.

Whereby answered 20/11, 2019 at 15:55 Comment(0)
H
14

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

Hankering answered 20/11, 2019 at 16:17 Comment(1)
Does public_api.ts just a convention, but this still doesn't stop users from importing something inside the Angular library?Southwester
S
8

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'
Synapse answered 20/11, 2019 at 16:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.