How to Create and Publish an Angular Library

How to Create and Publish an Angular Library

How to Create and Publish an Angular Library

Angular libraries let you share components, services, and directives across multiple projects — published to npm or a private registry.

Step 1 — Create a Library Project

# Create a workspace for the library
ng new my-workspace --no-create-application
cd my-workspace

# Generate the library
ng generate library my-ui-lib

# Generate a component inside the library
ng generate component button --project=my-ui-lib

Step 2 — Export Public API

// projects/my-ui-lib/src/public-api.ts
export * from './lib/button/button.component';
export * from './lib/card/card.component';
export * from './lib/services/theme.service';

Step 3 — Build and Pack

# Build the library
ng build my-ui-lib

# Navigate to the dist folder
cd dist/my-ui-lib

# Test locally with npm link
npm link

# In another project
npm link my-ui-lib

Step 4 — Publish to npm

cd dist/my-ui-lib
npm publish --access public   # for scoped packages: @org/my-ui-lib

Step 5 — Use in Another Project

// Install
npm install my-ui-lib

// Use in a standalone component
import { ButtonComponent } from 'my-ui-lib';

@Component({
  standalone: true,
  imports: [ButtonComponent],
  template: `<lib-button variant="primary">Click</lib-button>`,
})
export class AppComponent { }
All Comments