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 npmjs.com
    • 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 npmjs.com (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';

app.module.ts

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';

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

app.component.html

<awesome-xxx-lib></awesome-xxx-lib>

and the final result is…..

amazing!! 🙂

library-running

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s