Creating Angular Libraries (ng generate library)
Libraries allow sharing code between multiple applications or publishing to npm.
Generating a library
Section titled “Generating a library”- Create a new library in an existing workspace:
ng generate library my-library- Generated structure:
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.jsonDeveloping the library
Section titled “Developing the library”- 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.jsonto define the entry point and external dependencies.
Building and publishing
Section titled “Building and publishing”- Build the library:
ng build my-library- Navigate to the output folder:
cd dist/my-library- Publish to npm (or use a local link):
npm publishOr create a local link for testing:
npm link cd ../my-app npm link my-libraryUsing the library in an application
Section titled “Using the library in an application”npm install my-libraryThen import the module:
import { MyLibraryModule } from "my-library";
@NgModule({ imports: [MyLibraryModule],})export class AppModule {}Explanation:
ng generate librarycreates a structure ready for packaging.
- The
public-api.tsfile controls what is exposed to consumers. - Building produces a
dist/folder ready to publish. - Use
npm linkto test locally before publishing.