How to write a library for Angular 2 and publish it to NPM

Using modular code is a good idea, and nothing is more modular than writing a library. Like this you can just publish your library to npm and then use it in all your projects. This can be useful if you have a component you want to reuse or share,  a service or just any piece of code that you think can be reused between projects. But with typescript and Angular 2 writing your own library can be a bit daunting at first. Do you publish the typescript or the compiled javascript? Where does the result go, in a dist folder? What are best practices? What should I declare as dependencies of my library in my package.json?

Fortunately, you are not the first one to have come across those questions. Unfortunately, as things are changing rapidly, there are a lot of out of date answers when you Google for this problem. And even more so is there confusion as it seems to be immensely complicated to get a working Angular2 library. So this article aims at giving an up-to-date answer on how to create your ng2lib.

The currently best way to scaffold your Angular 2 library

So without further ado, this way is the best I’ve found so far to scaffold your Angular 2 library:

I think this is currently the best approach, since everything else simply will make you pull out your hair.

I’ve last checked if this is still the best solution in  June 2017.

Can I use angular-cli to create a standalone library?

As of March 2017, the angular-cli, which is used to create Angular projects and components, services etc for your project doesn’t offer a clear way to create a standalone library.


On a sidenote, if you just need to create a typescript library, no angular involved, you can checkout how-to-write-a-typescript-library.com!

One Reply to “How to write a library for Angular 2 and publish it to NPM”

Leave a Reply

Your email address will not be published.