Skip to content

Creating Angular Libraries (ng generate library)

Libraries allow sharing code between multiple applications or publishing to npm.

  1. Create a new library in an existing workspace:
Terminal window
ng generate library my-library
  1. Generated structure:
Terminal window
projects/
my-library/
src/
lib/
my-library.component.ts
my-library.service.ts
my-library.module.ts
public-api.ts # Public entry point
ng-package.json # Packaging configuration
package.json # Library dependencies
ng-package.json
package.json
  • Export components/services in public-api.ts:
export * from "./lib/my-library.module";
export * from "./lib/my-library.service";
export * from "./lib/my-library.component";
  • Configure ng-package.json to define the entry point and external dependencies.
  1. Build the library:
Terminal window
ng build my-library
  1. Navigate to the output folder:
Terminal window
cd dist/my-library
  1. Publish to npm (or use a local link):
Terminal window
npm publish

Or create a local link for testing:

Terminal window
npm link
cd ../my-app
npm link my-library
Terminal window
npm install my-library

Then import the module:

import { MyLibraryModule } from "my-library";
@NgModule({
imports: [MyLibraryModule],
})
export class AppModule {}

Explanation:

  • ng generate library creates a structure ready for packaging.
  • The public-api.ts file controls what is exposed to consumers.
  • Building produces a dist/ folder ready to publish.
  • Use npm link to test locally before publishing.