Up and running library development with Angular 7

Posted by Harald Nezbeda on Mon 28 January 2019

Developing libraries for Angular has become much smoother since version 7 of the framework. The Angular CLI is doing most of the boilerplate work, so developers can use the time to concentrate on coding.

Make sure you have the latest release of the Angular CLI.

ng --version

I used version 7.2.3 at the time I wrote this article.

Create workspace

The concept was introduced in Angular 7, and the CLI also received a new flag: --create-application

ng new my-lib --create-application=false

The command will generate a new workspace for Angular application and libraries with no default application, allowing now to add libraries and applications in the workspace and name them however required.

Create library

Libraries can be added via the CLI since version 6, but by using the workspace concept it makes things much cleaner.

ng generate library my-lib prefix=my

By using this command the CLI will create a new directory inside the workspace called projects. This where the library my-lib is located and it's also the place where future applications will be added. It also extends the paths configuration in the root tsconfig.json:

"paths": {
    "my-lib": [
        "dist/my-lib"
    ],
    "my-lib/*": [
        "dist/my-lib/*"
    ]
}

This allows to use the library inside the Workspace as if it is loaded from npm. It requires the library to be build inside the dist directory, which can be done by using the CLI:

ng build my-lib

Angular Library Build

The compiled library will be located inside the dist folder of the wokspace. It contains the code that will be loaded inside the workspace (this is also the code that can be publish on npmjs.com).

Create demo application

ng generate application my-lib-demo

Not necessary, but I highly recommend it as it will allow to test and create a documentation page for the library.

By using this approach the application my-lib-demo will be added also inside the projects directory. It will also create an application for e2e testing, as the regular cli command does.

Now you can got to the app.module.ts of the demo app and load the library.

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

import { MyLibModule } from 'my-lib';

import { AppComponent } from './app.component';

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

Include the default component from the library in the demo project. For a simple test I removed the content app.component.html that the CLI generated in the demo project and only added the component from the library:

<my-my-lib></my-my-lib>

Start the development server:

ng serve

And this is what the browser should display on http://localhost:4200

Angular Library Demo