Creating an Angular NPM Installable Service Library | Task

Ole Ersoy
Feb - 04  -  3 min


We need to publish a library to NPM for our peers.


We will be using the Angular Package Format, which should be a good way to package any NPM library as Angular supports all the popular package formats like FESM, UMD, etc. and does a good job of laying out your public API.

Angular CLI

npm install -g @angular/cli

New Workspace

ng new my-workspace --create-application=false
cd my-workspace

New Library

ng generate library my-lib


Within my-lib/src/lib remove everything except for: my-lib.service.ts. This is the only file that should be in public-api.ts:

 * Public API Surface of my-lib
export * from './lib/my-lib.service';


Build the library like this:

ng build --prod my-lib

Test Application

ng generate application libtest 
cd projects/libtest

Add the Library Service to Test Application

This is already done because of the workspace tsconfig.json configuration:

"paths": {
    "my-lib": [ "dist/my-lib"

When we built the library the build was placed in dist/my-lib, thus our test application can just import the service into app.component.ts like this:

import { MyLibService } from 'my-lib';

Note though that if using VSCode then open up the entire workspace (The root workspace folder).

This is such that the Tooling can see the tsconfig.json file and thus the path to the library.

To test that our application starts, from the root workspace run:

ng serve -o

Build the Library

First switch off Ivy in tsconfig.lib.json otherwise Angular will complain when attempting to publish to NPM:

"angularCompilerOptions": {    ...
    "enableIvy": false

Then build the library:

ng build --prod my-lib

Test NPM Publishing

Since this is just a test project we want to see what NPM would package for publishing, instead of actually publishing.

We can do a dry run like this:

cd dist/my-lib
npm pack

It will display what files are going to be uploaded and create a tar ball in the current directory.

We can also install this tarball into our test app like this (First we need to be in the workspace directory):

cd ../.. 
npm install my-lib

Look at the package.json file and notice that the my-lib library is now included via a file URL pointing at the tar ball:

"my-lib": "file:dist/my-lib/my-lib-0.0.1.tgz"

We can now develop our service further and when it’s ready to our first publish:

npm publish --access public