Getting Started Building Component Libraries with Angular CLI
Tags: javascript, angular, angular6, angularcli
Published: 2018-06-04 05:41:56

---
title: Getting Started Building Component Libraries with Angular CLI
published: true
tags: javascript,angular,angular-6,angular-cli
canonical_url: https://medium.com/@brenden.niedermeyer/angular-cli-libraries-79b0a32a1443
---

![](https://cdn-images-1.medium.com/max/1024/1*IQ9QA3Sy1kX7XdmZmFwlYg.jpeg)<figcaption>Photo by <a href="https://unsplash.com/photos/JuFcQxgCXwA?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Samuel Zeller</a> on <a href="https://unsplash.com/search/photos/package?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption>

One of the things that’s always had a higher barrier of entry in the Angular ecosystem is creating libraries of components that other Angular apps can use. The Angular team published guidance with things like the [Angular Package Format](https://docs.google.com/document/d/1CZC2rcpxffTDfRDs6p1cfbmKNLA6x5O-NtkJglDaBVs/edit) and from that the community has created some fantastic tools, like [generator-angular2-library](https://github.com/jvandemo/generator-angular2-library), that make it easier. However, there was never a tool that generated opinionated implementations of the Angular Package Format the same way that developers who used the Angular CLI in their normal project workflows were used to.

With the recent release of version 6 for the Angular CLI, we now have access to tools that can help us build libraries while still taking advantage of other powerful aspects of the CLI, such as schematics, without leaving the workflows we are used to! I will show you how to the CLI to get started building your own component libraries.

We’ll cover:

- Generating a library project with the Angular CLI
- Building components for your library
- Using your library in other applications
- Publishing your library for others to use

### Generating a library project with the Angular CLI

First thing’s first. We need to setup our project. If you don’t have the latest version of the CLI grab it from npm.

{% gist https://gist.github.com/bniedermeyer/0ab300b569afc80bd575f52d0eb617b6 %}

Now create a new project with the CLI. Nothing new here.

{% gist https://gist.github.com/bniedermeyer/51fe5d681ac9d00d7a722bd461d61143 %}

If you’re used to working with the Angular CLI you might notice a couple changes to the project structure you know and love. The most noticable of which is that the old angular-cli.json is gone and now replaced with a new angular.json file.

This file is the key to one of the biggest new features in version 6. Now the Angular CLI can create and work with workspaces that contain one or more multiple Angular projects. This angular.json file gives you control over the configuration of each of those projects. This is ultimately what makes building of libraries within the CLI possible because we need handle the building of libraries differently than we normally would for normal Angular apps.

Ok — so now we know a bit more about how libraries within CLI pojects work; let’s generate the library structure in our project. We do this with the generate command just like we would to create a component, service, module, etc...

{% gist https://gist.github.com/bniedermeyer/4ddae7c1936012fee4a0a1fa87669b67 %}

This creates a new /projects directory with a new folder for your library and some example files.

The files to really take note of here are /src/public\_api.ts, ng-package.json, and ng-package.prod.json. These files control the configuration for [ng-packagr](https://github.com/dherges/ng-packagr) - the library that powers the packaging of your library. I encourage you to check out the project and familiarize yourself with how it works, but here is a quick and dirty overview:

- public\_api.ts is the new entry point for your library. If you have any files that you want accessable to consumers of your library (modules, components, etc...) you need to export them here in addition to exporting them from whatever modules are in your library.

{% gist https://gist.github.com/bniedermeyer/2013e645c16599e389ac54adeda8eb65 %}

- ng-package.json and ng-package.prod.json control the configuration for the packaging process that ng-packagr performs. You can use them to change things like the destination build directory or defining a different entry point for your app. ng-package.json is used during your ng build command and ng-package.prod.json is used when you run ng build --prod. The only difference between these two files right now is that ng-package.json contains a deleteDestPath flag that will delete your destination directory before running a build. This will be helpful during development when you are constantly making changes.

> **_Protip_** _: if your library needs to do something like bundle an overall Sass file, you will need to include something like_ [_scss-bundle_](https://github.com/SimplrJS/scss-bundle) _in your workflow._ [_See here for more information_](https://github.com/dherges/ng-packagr/issues/273#issuecomment-345059670)

### Building components for your library

Now we have the general structure for our library setup. It’s time to start building!

First add [Angular Material](https://material.angular.io/) to our project.

{% gist https://gist.github.com/bniedermeyer/d7811214ff1c3bbbec3da037f31b90e5 %}

“Wait, why are we adding Material to my-app and not my-new-lib?” Good question. The easy answer to that question is that in this case Material is a peer dependency of our library. We don’t want it to be downloaded each time our library is installed somewhere — that can lead to things like huge final bundles when the application is built. Instead we want to mandate that whichever project is using our library needs to also have Material installed as well. For libraries that will be installed and consumed by third parties (hint, hint: ours) you’ll need to add things like Material to the peer depencies. There’s a good discussion about when to use peer vs. normal depencies [here](https://stackoverflow.com/questions/26737819/why-use-peer-dependencies-in-npm-for-plugins).

Additionaly, the ng add command for Material only works for standard project configuration, i.e. those generated by the ng new command. If you were to run ng add @angular/material --project my-new-lib you would get an error saying so. The schematic that is being run in the background to add Material assumes you are adding it to an existing Angular app and not a library so it won't understand since the structure inside angular.json that is setup for your library.

Go ahead and add to our peer dependencies now.

{% gist https://gist.github.com/bniedermeyer/228586066f756049ec48c57b6d50c5f3 %}

Let’s setup the module for our library. First, delete the example files that were generated by the CLI in src/lib and from public\_api.ts. Then generate the module.

{% gist https://gist.github.com/bniedermeyer/fc56f49223b2b8a4f3393717bb136736 %}

Since we will want others to consume this module we need to add it to public\_api.ts.

{% gist https://gist.github.com/bniedermeyer/9e1f445facaca0e122556c7efc9ee1b7 %}

For this example the library will have a component that consists of a button and a badge. Each time the button is clicked the badge will update and show the total number of clicks. For added complexity the component should also emit an event to let any parent component know that the count has changed and what the current count is.

First generate the component.

{% gist https://gist.github.com/bniedermeyer/6654938f50f7779ae321137bc2239408 %}

Export the component that was just created from our library. Also import the MatBadgeModule and MatButtonModule while you are here.

{% gist https://gist.github.com/bniedermeyer/632deb47abd34178d6c840a0703ca196 %}

Also add the component to public\_api.ts

{% gist https://gist.github.com/bniedermeyer/8a9754756e9e8f1d581919a2d939db22 %}

Now add logic to the component to handle incrementing the count displayed whenever the button is clicked.

{% gist https://gist.github.com/bniedermeyer/93bd3d76efe324942a6ff5eaef2dfd25 %}

Next we’ll wire up the component to the template.

{% gist https://gist.github.com/bniedermeyer/4d2f7f1c709b83d398ec7344f2e3438c %}

Now we have a component that we want other apps to use! But how do we make sure it works? We’ll handle that next.

### Using your library in other applications

Alright, we have an awesome library ready for use — but how do we actually use it? There’s a couple of different ways.

The first is to use it within the application that was generated by the CLI when we first started our work. Remember, the Angular CLI doesn’t just generate a single app anymore; instead it generates what the CLI team refers to as a workspace. This means you can build multiple apps and libraries in the same directory and utilize what you built within other projects in the same workspace.

Open up tsconfig.json in the root of your workspace. You'll see a paths option that points to a dist/my-new-library directory.

{% gist https://gist.github.com/bniedermeyer/1b34a07b2aee123b228641bfd3953ac8 %}

What this does is allow you to automatically use your library, after it’s been built, in other apps in the same workspace. This works similarly to using libraries installed by npm in that you can just import your components and use in your library. This of course means that you _must_ build any libraries that your app depends on **before** you build your app, and will need to rebuild it every time you make a change to the library before those changes will be reflected.

A sample workflow could work like this:

{% gist https://gist.github.com/bniedermeyer/1ec98aff845b00c842971558694d6ebe %}

Now go ahead and build our library, then we will build an example of how to use it using the original app generated in our workspace.

{% gist https://gist.github.com/bniedermeyer/3651851000f11cf502ab6ba983161f63 %}

This generates the dist/ directory mentioned eariler. If you open that directory and take a look you'll see that ng-packagr has generated FESM2015, FESM5, and UMD bundles of the library for consumption and generated a types file.

Now we are ready to use the library in our app!

Import the MyLibModule in src/app/app.module.ts

{% gist https://gist.github.com/bniedermeyer/0d936b2ea209f3bb9e38bcebf6221e29 %}

We want to demonstrate that the app is receiving the countChanged events from the library component so implement handleCountChanged() in src/app/app.component.ts.

{% gist https://gist.github.com/bniedermeyer/6ebe41e59849ffa7478effe6484a37e5 %}

Now add the CounterButtonComponent to src/app/app.component.html. Also add a div that shows the values being emitted from the component.

{% gist https://gist.github.com/bniedermeyer/3f48e472aaa122afa250efffc255394b %}

Let’s see our example app in action! Remember to build your library before serving the app.

{% gist https://gist.github.com/bniedermeyer/05c98fb64b8a766b191b246bf2539efc %}

Open the browser and you’ll see your component in action!

![](https://thepracticaldev.s3.amazonaws.com/i/p96n22t442irmjb076kw.gif)

Using libraries like this is a great way for you to share code between multiple Angular apps in the same workspace. Additionally, if you are building something like a component library you could use the originally generated Angular app to build great working examples for your library.

### Publishing your library for others to use

So, you’ve built an awesome component library and are using it in your own applications, but what if you want to share it so others can use it in their apps?

First, if you haven’t published anything on npm before go ahead and sign up.

{% gist https://gist.github.com/bniedermeyer/01245f7bb243751d03a45b240c308130 %}

After you sign into your npm account, build the library again. This time use the --prod flag so that the Angular CLI will perform some additional steps for optimization.

{% gist https://gist.github.com/bniedermeyer/09fca89a16ead9da3d1e1b3858e21dca %}

Now move into dist/my-new-library. If you want to test that your package will work in other apps you can link it to your local npm registry.

{% gist https://gist.github.com/bniedermeyer/f4bbef83d15926749cf97fa3519a8842 %}

Now create a new Angular workspace and link your library to the project.

{% gist https://gist.github.com/bniedermeyer/def5210fa6d7eac5c84f64acfa993024 %}

In the new workspace add preserveSymLinks to angular.json in the options object under projects/test-lib-app/architect/build. This allows the linking of your library to continue working when the app is served.

{% gist https://gist.github.com/bniedermeyer/e6a72d31723e0e9b97a2119bf64505b4 %}

Use the library in the same way we did eariler and you see that it will work here as well! To remove the linked library you can use an npm remove my-new-library command in the test project and the npm unlink command in the directory of your built library.

If you are ready to publish your app to npm for others go ahead and run the below command inside of your dist/my-new-library directory.

{% gist https://gist.github.com/bniedermeyer/44daabaadcf12ef59249a01c1d7053d7 %}

From there you can use it as you would any other packages using npm install.

### Next Steps

Congratulations! You have built your component library with Angular and have published it to npm for others to use. Go forth and build cool libraries to share! For next steps I also highly encourage you to dive into the documentation for [ng-packagr](https://github.com/dherges/ng-packagr/issues?q=label%3Adocumentation%20) to learn about more advanced topics regarding the library packaging process.

You can find the code used in the examples in Github [here](https://github.com/bniedermeyer/component-libraries-with-angular-cli).