Using Shared Libraries (Workspace, Projects)
Large Angular applications often share code across multiple projects.
Angular Workspace (monorepo) allows you to create one or more libraries alongside your main application.
This section explains how to create, build, and use shared libraries in Angular 21.
Setting Up an Angular Workspace with a Library
Section titled “Setting Up an Angular Workspace with a Library”Generate a new workspace with a library:
ng new my-workspace --no-create-applicationcd my-workspaceng generate library my-libThis creates a projects folder with my-lib containing its own source, tests, and a public-api.ts file.
my-workspace/├── projects/│ ├── my-lib/│ │ ├── src/│ │ │ ├── lib/│ │ │ ├── public-api.ts│ │ │ └── test.ts│ │ ├── ng-package.json│ │ └── package.json├── angular.json└── package.jsonYou can also generate an application within the same workspace:
ng generate application my-appNow you have projects/my-app and projects/my-lib.
Building the Library
Section titled “Building the Library”Build the library using the CLI:
ng build my-libThe output goes into the dist folder. For development, you can use watch mode:
ng build my-lib --watchUsing the Library in the Application In the application, import the library module or standalone entities.
If your library exports an NgModule:
// projects/my-app/src/app/app.module.ts (if still using modules)import { MyLibModule } from 'my-lib';
@NgModule({imports: [MyLibModule]})If your library exports standalone components (recommended in Angular 21):
// projects/my-lib/src/public-api.tsexport * from "./lib/my-component/my-component.component";Then in the app component:
// projects/my-app/src/app/app.component.tsimport { Component } from '@angular/core';import { MyComponent } from 'my-lib';
@Component({ selector: 'app-root', standalone: true, imports: [MyComponent], template: <lib-my-component></lib-my-component>})export class AppComponent {}Path Mapping for Local Development The CLI automatically adds a path mapping in the root tsconfig.json so you can import the library by its name:
// tsconfig.json{ "compilerOptions": { "paths": { "my-lib": ["./dist/my-lib"] } }}This points to the built output. For a smoother development experience (without rebuilding after each change), you can use “my-lib”: [“projects/my-lib/src/public-api.ts”] to reference source directly, but be aware of potential duplicate Angular instances. The recommended approach is to build with watch.
Publishing the Library
Section titled “Publishing the Library”To publish to npm, first build the library, then publish the dist folder:
ng build my-libcd dist/my-libnpm publishMake sure the library’s package.json (inside projects/my-lib) has correct metadata (name, version, peerDependencies).