AngularComponentLibrary
This project is to understand how to create npm ready angular component libraries to use in an angular application.
After, generating an angular application for the demo we will follow below steps to create component library
- Generate a library project by running following command
ng generate library ratify --prefix=lib
- Library project will be created with one default exported component
lib-ratify
- Lets write some code snippet to make
lib-ratify
to behave like a rating component. - We can find the source code of rating component here
- To build the library run the below command
ng build ratify
- Built is added to the dist folder of our application as
dist/ratify
- There are two ways angular registers external libraries.
- NPM Module declarations in the
package.json
file. - Library registered in the
tsconfig.json
file
Note: Since we generated library with our application. Angular registered our library by placing library dependency entries in
angular.json
andtsconfig.json
- NPM Module declarations in the
- We have added few scripts to built the library and pack for npm in
package.json
"scripts": {
...
...
"build-lib": "ng build --prod ratify",
"npm-pack": "cd dist/ratify && npm pack",
"package": "npm run build-lib && npm run npm-pack"
}
Last three commands (build-lib, npm-pack, package) are responsible for building and packing the library for npm
- Run
npm run package
to create npm ready library indist/ratify
Finally, lets see how to publish npm package
- Add npm user by running below command
npm adduser
Note:
- If you are not signed up above command will sign up you as npm user.
- Type
npm whoami
from a terminal to see if you are already logged in (technically, this also means that your credentials have been stored locally).
- Login into npm by running
npm login
- Go to the packaged output in
dist/ratify
> cd dist/ratify
> dist/ratify> npm publish
npm package will be uploaded to the npm registry - angular-ratify