Creating and Publishing an Angular Library: A Quick Guide

This page provides a brief guide on creating an Angular library and publishing it using Npm

Getting started

Project creation

To start, I created an Angular project with these commands:

ng new my-workspace --no-create-application
cd my-workspace
ng generate library my-lib

This will allow the dist folder of the project to display a lib folder with a default component. Within lib you will be able to add the component you want to make shareable through the library.

Build and test

The first step is to make a build of the project as follows:

ng build my-lib

This creates a dist folder with the compiled source code.

Now to do some testing you can use npm link. CAUTION To use it properly you must navigate to the dist folder and once inside run the following command:

cd dist/my-lib
npm link

After that, go to an OTHER project where you want to test the library and run the following command by passing the name found within the package.json of the dist folder:

dist/my-lib/package.json

{
"name": "my-lib",
"version": "17.0.1",
...
npm link my-lib

This way inside the project where you want to test the library will be present in the node_modules the library and not in the package.json.

Publication

To publish the library after the build is done, it is necessary to browse of in the generated dist file with the compiled source code and after that do the following npm publish command to publish the library:

ng build my-lib
cd dist/my-lib
npm publish

Finally you will be able to use the library by installing it as follows:

npm i my-lib