Developing a Simple Angular Library

Intro

If you want to be able to easily develop, test, and publish an angular library to npm then follow these steps. Here I’ll be showing what I did to get my library ‘ngx-js9’ published to npm.

Library Development

On your local machine, create a regular angular application with a name of the form “ngx-XXX-library”:

ng new ngx-js9-library
cd ngx-js9-library

I’ll refer to this regular app we just created as the “wrapper (app)”. Within this wrapper app, we will now generate a library with a name of the form “ngx-XXX”:

ng generate library ngx-js9

The code for the library will be in projects/ngx-XXX, and the code for the wrapper will be in the usual src dir. We now compile the library with:

ng build ngx-js9

This command outputs to dist/ngx-XXX. Within the wrapper app we can import this library by going to app.module.ts and importing the library module as follows:

...
import { NgxJs9Module } from 'ngx-js9';

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

Now go to app.compnent.html and make the following the content:

<h1>Lib Test</h1>
<lib-ngx-js9></lib-ngx-js9>

… and run the app as per usual with ng serve, and you’ll see the content of the library component embedded within the wrapper app. Now for hot-reloading development of your library component, you can also build the library with the --watch option:

ng build ngx-js9 --watch

… along with ng serve in order to get instant updates. Awesome — angular has made things very straightforward to set up and develop a basic library!

Publishing to npm

If you are signed into npm then all that’s involved is to run npm build ngx-XXX, then go into the generated dir dist/ngx-XXX and run npm publish. It’s that simple!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *