Angular Key Concepts

How to Create and Use a Package in Angular

How to Create and Use a Package in Angular

When working on large Angular applications, you may want to reuse code across multiple projects. Instead of copying and pasting code, the best approach is to create an Angular package (library) and then use it wherever needed. In this blog post, we’ll walk through the step-by-step process of creating, building, and using an Angular package.


1. Create an Angular Library

Angular CLI makes it easy to generate a library inside your workspace. Run the following command:

ng generate library my-lib

This will create a new library project under projects/my-lib/.


2. Develop Your Library

Inside projects/my-lib/src/lib/, you can create components, services, directives, or modules.

Make sure to export them via the public-api.ts file:

export * from './lib/my-lib.service';
export * from './lib/my-lib.component';
export * from './lib/my-lib.module';

This ensures they are accessible when the library is used in another project.


3. Build the Library

Once your code is ready, build the library:

ng build my-lib

The compiled output will be located in dist/my-lib/.


4. Package the Library

Navigate to the dist folder of your library:

cd dist/my-lib

Create a package file:

npm pack

This will generate a .tgz file (e.g., my-lib-0.0.1.tgz).


5. Use the Library in Another Project

You have two options to consume the library:

Option A: Local Install

Install it directly from the .tgz file:

npm install ../path-to/dist/my-lib/my-lib-0.0.1.tgz

Option B: Publish to npm

If you want others to use it, publish it to npm:

npm login
npm publish

Then install in another Angular project:

npm install my-lib

6. Import the Library into Your Project

Once installed, import the library module in your app.module.ts:

import { MyLibModule } from 'my-lib';

@NgModule({
  imports: [
    BrowserModule,
    MyLibModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Now you can use your library’s components and services anywhere in your project.


Final Thoughts

Creating Angular libraries is a great way to:

  • Reuse code across multiple projects
  • Maintain a clean and modular architecture
  • Share functionality with other teams or the open-source community

Whether you’re publishing to npm or just keeping it for internal use, Angular’s built-in library support makes the process straightforward.

Next step: If you’re working with multiple apps, consider setting up a monorepo workspace so all projects and libraries live in the same workspace for easier management.

Leave a Reply

Your email address will not be published. Required fields are marked *