How to create an Angular library or package and publish on npm
Emeka Elo-Chukwuma
Posted on July 19, 2022
What are libraries?
Libraries which are also known as packages are reusable codes that speed up development processes or add functionalities to our applications. They save time, energy and resources for developers.
When building an Angular application, you may find yourself rewriting functionalities you implemented across your app or projects. That can seem counter productive and a solution to that is to refactor that functionality or feature into a library which would make it more reusable, maintainable and accessible. This article shows how to create libraries or packages for the angular ecosystem. Let's begin!
Requirements
Angular framework (version 14)
Node version ^14.15.5 || ^16.10.0
If you want to use a different angular version, you can check this angular and node version compatibility table made by @layzee
Just keep in mind that libraries built with higher versions of angular are not compatible with applications built with angular versions lower than that of the library.
Setting up the library
We will be using the Angular CLI to set up a workspace where we will build the library and an angular application where we can check out the functionalities we built for the library. Let's name the workspace library-app and create it with the following command:
ng new library-app
When it's done, you can serve your application to see it running.
Enter the root directory of your new workspace and generate the library with the following command:
cd library-app
ng generate library ngx-stuff
Here, the name of our library is ngx-stuff. This is going to be a library that just does stuff π€―.
The ngx prefix is a convention to denote that the library can be used with Angular.
After the command, a projects/ngx-stuff folder with the structure below is created in the root directory.
The lib folder contains the files where the library features are built.
The public-api.ts exposes the functions and utilities to be imported by other applications.
The package.json records important metadata about the library and is required before publishing to NPM. It also defines functional attributes of the library that npm uses to install dependencies and identify the entry point to our package.
An ng-packagr library is installed in the workspace and can be seen in the package.json of our application.
The build output path for the library is added to the tsconfig.json.
The angular.json file is modified by adding configuration for the generated library which basically maps the file paths in the library folder to properties in the json file.
Notice the different projectType for the ngx-stuff library and the library-app application
Building features in the library
The type of functionality we want to build into a library is determined by the kind of library it is. There are component or ui libraries as well as utility libraries. Your library can also be both if you want.
Utility feature
To build utility functions for our library, we create reusable functions in the ngx-stuff.service.ts file.
Let's create two functions called doStuff that returns the string stuff library and doStuffWithInput that returns the string we pass to the function as an argument.
Now, we can instantly use these functions from the library in our application by injecting the library service as a dependency using the Angular 14 inject() method
// app.component.tsimport{Component,OnInit}from'@angular/core';import{NgxStuffService}from'projects/ngx-stuff/src/public-api';@Component({selector:'app-root',templateUrl:'./app.component.html',styleUrls:['./app.component.css'],})exportclassAppComponentimplementsOnInit{title='library-app';stuff=inject(NgxStuffService);ngOnInit(){console.log(this.stuff.doStuff());console.log(this.stuff.doStuffWithInput('stuff library with input'));}}
When we run our application, we can see the values we logged out in the browser console.
Component feature
To add a component feature to the library, we build the user-interface in the ngx-stuff.component.ts file. We will create a reusable button that can be customized.
The field properties in the component class are bound to the attributes in the button. These properties have the Input() decorator which allows the library to receive values from parent components(components where the library is imported).
To use the ngClass and ngStyle attributes, the commonModule package needs to be imported in the library's module.
Notice that the import path for the library looks a bit different, that's because we are importing the library locally relative to where we want to use it in our application. However, in our tsconfig.json, the path has already been configured for the build path to map to a shorter string which is easier to understand.
So now, when we make any change to the library, we need to build it first before checking it out.
Publishing to NPM
To publish a library or package to npm, a user account on npm platform is needed. You can sign up here if you do not have an account.
Now we need to log in to our npm account via the terminal on vscode using the following command;
npm adduser
Answer the prompts for your username, password and email. You will also get another prompt to fill a one time password sent to your email. Once it's done, the terminal will show Logged in as <username> on https://registry.npmjs.org/.
You can also use the npm whoami command which will return your username in the terminal to verify you are logged in.
Build the library using the ng build command then
navigate to the build output folder using the command below
cd dist/ngx-stuff
Run the command below to publish the package to npm
npm publish
Yay! π₯³ you just published your library.
The published library built in this article can be found here.
You can checkout the repository for the entire project.
An angular application with a library project published to npm
LibraryApp
This project was generated with Angular CLI version 14.0.5.
Development server
Run ng serve for a dev server. Navigate to http://localhost:4200/. The application will automatically reload if you change any of the source files.
Code scaffolding
Run ng generate component component-name to generate a new component. You can also use ng generate directive|pipe|service|class|guard|interface|enum|module.
Build
Run ng build to build the project. The build artifacts will be stored in the dist/ directory.
Run ng e2e to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
Libraries are essential to the software development process and I hope this article has helped you understand how to build libraries or packages in Angular. Let me know if you have any comments or suggestions in the comment section and lastly, feel free to share the article so that others can learn. Happy publishing!
Connect
If you would like to connect with me, I'm available on;