When you are planning your Angular application, you will need to share some features across multiple applications and put it up in public npm or internal npm that your organization uses. In that scenario what should you do? The solution is to create a custom angular library. In this article, I’m going to guide step by step to create a custom library using Angular. For creating an Angular custom library you should use Angular 6 or higher version.
Step 1
ng new custom-library-app
Step 2
After creating an Angular project, run the following command to create your first Angular library.
Now, this is going to scaffold out an entirely new project,
which is the library project.
ng generate library event-bus
I have created an Event Bus Service for component communication. my plan is to share that service across multiple applications. this is the event bus service.
After creating the library you'll notice that we have a projects folder.
We also now have an updated tsconfig. It added the paths to where ultimately we're going to be building our dist folder once we do a build, and that's why you have to build first before you can do this because TypeScript is actually going to look here to be able to make this all work.
Now the other big thing that's been done is our angular.json file has a new project in it.
You can see lib folder, public-api and other relevant files inside the library project. inside the lib folder, you can identify service, model and component files. Now I'm going to add my event bus service code to an angular custom library.
Step 3
Build your library project running the following code.ng build event-bus
We are almost ready to deploy our Angular custom library to npm.Before that update package.json file with additional details such as author, github link, etc.
Step 4
If you are not a user in npm registry, create an account running the following command.
Github>>>
npm >>>
npm adduser
Step 5
After creating a user log in to npm using the following command.
After publishing your library you'll be able to install that library as a npm package and that can be used across the multiple applications.
npm login
Step 6
Go to the dist/event-bus folder path and run the npm publish command.
npm publish
Github>>>
npm >>>
Comments
Post a Comment