Chuyển đến nội dung

Bài 58 · Tooling and Ecosystem

Building and Publishing an Angular Library

Create a reusable Angular library with the CLI, design its public API, set peer dependencies, build it with ng-packagr and publish it to npm. Includes runnable stand-ins for the checks.

At some point you write a component, pipe or service that a second app needs. Copying files between repositories works for a week and then the copies drift apart. The Angular answer is a library: a package with its own version, built once and installed with npm install. Angular Material, the Router and NgRx are all libraries built this way.

In this lesson you will create a library in a workspace, decide what it exposes, build it, test it against a real app and publish it. Basic CLI knowledge from Setup and the Angular CLI and the project layout from Project Structure and Best Practices will help.

Real versus stand-in. The CLI commands, package.json files and Angular code are real and read-only: the site cannot run ng build or publish to npm. The runnable examples re-create two checks in TypeScript: finding what a public API exports, and validating a version range for peer dependencies. They are simplified models, not the real tools.

Why a library and not a folder

Approach Good for Cost
A shared folder in one app Code used in one app Cannot be reused elsewhere
A library in the same workspace Several apps in one repository (a monorepo) Needs a public API; changes are seen immediately
A published npm package Many teams or the public Versioning, release process, compatibility promises

Start with a workspace library. You can publish it later without changing the code.

Creating a library

Inside an existing workspace, generate a library project:

Terminal
ng generate library ui-kit --prefix=ui

The CLI adds a projects/ui-kit folder and a build target in angular.json:

TEXT
projects/ui-kit/
  package.json          (the package published to npm)
  ng-package.json       (settings for ng-packagr)
  tsconfig.lib.json
  tsconfig.lib.prod.json
  tsconfig.spec.json
  src/
    public-api.ts       (the only entry point other code may use)
    lib/
      badge/badge.ts

Write the library like any Angular code. Components use the modern style with a prefix that avoids clashes with other libraries:

TypeScript
// projects/ui-kit/src/lib/badge/badge.ts
import { ChangeDetectionStrategy, Component, input } from '@angular/core';

@Component({
  selector: 'ui-badge',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `<span class="badge" [class.badge-warn]="tone() === 'warn'"><ng-content /></span>`,
  styles: `
    .badge { padding: 0 0.5rem; border-radius: 999px; background: var(--ui-badge-bg, #e0e7ff); }
    .badge-warn { background: var(--ui-badge-warn-bg, #fde68a); }
  `,
})
export class Badge {
  tone = input<'info' | 'warn'>('info');
}

Notice the CSS variables with defaults: consumers can restyle the component without reaching into its internals, which suits view encapsulation.

The public API

public-api.ts decides what the outside world can import. Anything you do not export here is private, even if the file exists:

TypeScript
// projects/ui-kit/src/public-api.ts
export * from './lib/badge/badge';
export * from './lib/format-bytes.pipe';
export type { Tone } from './lib/tone';

This file is a promise. Once other apps import Badge, renaming or removing it is a breaking change that needs a new major version. Export deliberately and keep internal helpers out.

TypeScript Which names does a public API expose?

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The real tooling works at the TypeScript level, but the rule is the same: additions are minor, removals are major.

Dependencies: peer, not bundled

A library should not ship its own copy of Angular. If an app and a library each had their own @angular/core, dependency injection and change detection would break. So the library lists Angular as a peer dependency: "I need this, but the app provides it".

JSON
{
  "name": "@acme/ui-kit",
  "version": "1.0.0",
  "peerDependencies": {
    "@angular/common": "^20.0.0 || ^21.0.0",
    "@angular/core": "^20.0.0 || ^21.0.0"
  },
  "dependencies": {
    "tslib": "^2.3.0"
  },
  "sideEffects": false
}

tslib is a normal dependency (small helpers). "sideEffects": false tells bundlers they may drop unused exports, which enables tree-shaking. A wide peer range lets more apps install the library; the cost is that you must test against each major version you claim.

The check an installer performs is easy to model:

TypeScript Does the app satisfy the peer range?

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Building with ng-packagr

The CLI builds libraries with ng-packagr. It compiles the code, creates the package metadata and outputs the formats modern bundlers need:

Terminal
ng build ui-kit

The output goes to dist/ui-kit (a folder with package.json, bundled ESM files, type declarations and an exports map). Two details matter:

  • Partial Ivy compilation. Libraries are compiled to a stable, intermediate format. The application's build finishes the compilation with its own Angular version, which is why a library built with one Angular release can run in an app that uses a newer one. You never publish fully compiled Ivy code.
  • Secondary entry points. A big library can be split so apps import only what they need, for example @acme/ui-kit/table. Each entry point is a folder with its own ng-package.json and public-api.ts.

You create an entry point by hand: add a folder such as projects/ui-kit/table with a minimal ng-package.json:

JSON
{ "lib": { "entryFile": "src/public-api.ts" } }

Testing it with a real app

Inside the workspace, an app can import the library by its package name. The CLI adds a path mapping to tsconfig.json that points to dist/ui-kit after a build:

JSON
{
  "compilerOptions": {
    "paths": {
      "@acme/ui-kit": ["./dist/ui-kit"]
    }
  }
}
TypeScript
import { Component } from '@angular/core';
import { Badge } from '@acme/ui-kit';

@Component({
  selector: 'app-root',
  imports: [Badge],
  template: `<ui-badge tone="warn">3 new</ui-badge>`,
})
export class App {}

Build the library first (ng build ui-kit --watch in one terminal), then ng serve the app in another. To try the package outside the workspace before publishing, run npm pack in dist/ui-kit and install the resulting .tgz in another project: this is exactly what your users will get.

Publishing

The steps, in order:

Terminal
ng build ui-kit --configuration production
cd dist/ui-kit
npm pack --dry-run        # check which files would be published
npm publish --access public

Before the first publish, check these items: a unique package name or a scope such as @acme/, a README.md and LICENSE, a correct version, and a files list or .npmignore that leaves out source files you do not want to ship. Never publish from the source folder; always publish the dist folder. Follow semantic versioning: patch for fixes, minor for additions, major for removals or incompatible behavior.

When a new Angular major arrives, release a version whose peer range includes it, after running your tests against it. Many libraries also run the build in CI against the minimum and maximum supported Angular versions.

Schematics, briefly

A schematic is a code generator and migrator that runs with ng add or ng generate. A library can ship one so that ng add @acme/ui-kit installs the package, adds providers to app.config.ts and imports a stylesheet. Schematics are optional and a bit advanced: they are built on the @angular-devkit/schematics package and described in a schematics entry in package.json. Add one when installation needs more than npm install, for example setting up a theme.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What decides which symbols other projects can import from your library?

    public-api.ts is the entry point. Anything not exported from it is private, even if the file exists.
  2. 2. Why is @angular/core listed under peerDependencies in a library?

    Two copies of Angular in one app break dependency injection and change detection. A peer dependency says "the app provides this".
  3. 3. You remove an exported component in the next release. Which version bump follows semantic versioning?

    Removing a public export can break every consumer, so it is a breaking change and needs a new major version.
  4. 4. What should you publish to npm?

    The build output contains the package.json, bundles and type declarations that consumers need. Publish that folder.

Summary

  • A library packages reusable Angular code with its own version; start inside the workspace and publish later.
  • ng generate library creates the project, public-api.ts defines what is exposed, and removing an export is a breaking change.
  • Declare Angular as a peer dependency, keep tslib as a dependency and set "sideEffects": false.
  • ng build uses ng-packagr and partial Ivy compilation; apps finish the compilation.
  • Test with a path mapping or npm pack, publish the dist folder and follow semantic versioning.
  • Schematics let ng add configure a project for your library.
  • The CLI and Angular code here are real and read-only; the runnable examples are small stand-ins.

Next: Build and Deploy

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.