Creating An Angular Library And Publishing To NPM


The Angular libraries are created as a solution that can be reusable for one or more applications. The Library is a collection of precompiled routines that a program can use. An Angular library is an Angular project that differs from an application, and it can run the shared npm package on its own. A library must be imported into your application using the angular npm command.

Create an Angular Library

To create a library we are going to use a very simple command as below.
ng generate library library-name
First we have created a normal Angular application using the Angular commend. Please follow the below steps.
Now inside this Angular library application, follow the below command to create the library in our project.
Here the library name should be lowercase “testlibrary”
After executing this command please check the files. Some of the files have been created and updated. Mainly angular.json, package.json, and tsconfig.json are updated.
Please confirm changes in all 3 files
You can see package.json files that have their dependencies and version numbers.
Next, we are going to see the public-api.ts file inside the library src folder. public-api.ts is called the entry point of our library project.
Please check projects\testlibrary -> src->lib-> inside the path verify the all reusable components,services,modules. If we need more files we will add custom files also that file must be called the public.api.ts file finally.

Build an Angular Library

If we use the library first we are going to build the library first. Please follow the below library build command.
ng build testlibrary
After successfully building the library, the dist folder will be created. Inside the dist folder, our compiled library will besorted. Please check the changes in the above picture.
Now we can import and use the library same and other Angular applications.
Next we'regoing to add the app.module.ts file to the below import code.
import { LibModule } from ‘testlibrary ’;
Add the library tag into the app.component.html page
If we need any changes inside (component, service, directives) the library change the package version to high and build the library again.
We have successfully built and imported the library in our Angular project.