We will start this article as a tutorial to develop an Angular Component Library, consume it within an Angular CLI project, and then we will publish it to NPM. This will be a step-by-step guide.
Let’s see what exactly we are building as a component library. We have a following navbar or header.
Step 1: Create a Angular library app.
Here are the commands to create a component library.
ng new headerAppcd headerAppng g library angCommonHeader
Here is the project structure.
For reusable library code, need to define a public API for it, it is maintained in the
public-api.ts file in library folder.
In latest angular version there is not html and css file, we can create those manualy and add our html code and css code to html and css file respectively.
below is the code of html file.
Step 2: Import library module to main project module.
Import library module to app.module.ts to check localy.
here we imported library module to app.module.ts(line 6).
and in app.component.html file
Step 3: Run the application
Run the application by using ng serve, it will run on port 4200 (default), open browser.
Step 4: Publish your library.
Remove private: true flag from library package.json file and run
ng build angCommonHeader — prod
Now redirect to dist/ang-common-header, make sure you have npm account if not please create your account on https://www.npmjs.com/, after that come to terminal and enter
It will ask for credentials, enter your credn and after
Your done now.
here is my published npm package https://www.npmjs.com/package/ang-common-header
Step 5: How to use published library to other projects.
Like other library we can use our published library by using
npm i ang-common-header
And import module to the app.module.ts.