Create an Angular component library for npm

  1. ng new xxx-app that will be our testing application for our new library
  2. cd xxx-app
  3. ng g library xxx-lib --prefix=awesome
    • Mind that the components/services/modules that you would like to public expose must be specified in the file public-api.ts
  4. Rename the folder xxx-app to xxx-lib
  5. ng build xxx-lib
  6. cd dist\xxx-lib
  7. npm init to create the project.json file, that will contains the specs about your library
  8. Before publish:
    • You can create the file .npmrc if you need to push to a custom/private gallery. If you omit this, npm will try to push to the community gallery
    • The npm gallery authentication token must be saved in the user folder $HOME in the global file .npmrc
    • You can use the command npm login to automatically generate and save the token for (service like azure devops creates this token from the web interface and you save it to the global .npmrc there are also tools to do this, but I prefer to simply copy and paste the token myself)
  9. npm publish
  10. You can test the component directly from the application and the run ng serve as usual, this will execute the default application as if you had executed ng serve xxx-app. Now from the application you can use the component of your library without needing to install it from the gallery, and of course you can also debug it. From the app.module.ts imports the module XxxLibModule like this import { XxxLibModule } from 'projects/xxx-lib/src/public-api';


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { XxxLibModule } from 'projects/xxx-lib/src/public-api';

  declarations: [AppComponent],
  imports: [BrowserModule, XxxLibModule, AppRoutingModule],
  providers: [],
  bootstrap: [AppComponent]
export class AppModule {}



and the final result is…..

amazing!! 🙂


Npm tilde(~) and caret(^) in package.json version

The tilde matches the most recent patch version in the specified minor version.

~1.2.3 will match all 1.2.x versions but will miss 1.3.0.

The caret, on the other hand, is more relaxed. It will update you to the most recent minor version in the specified major version.

^1.2.3 will match any 1.x.x release including 1.3.0, but will hold off on 2.0.0.