loading...

Getting Started Building Component Libraries with Angular CLI

nieds profile image Brenden Originally published at Medium on ・8 min read

Photo by Samuel Zeller on Unsplash

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 and from that the community has created some fantastic tools, like 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.

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

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...

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 - 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.
  • 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 in your workflow. See here for more information

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 to our project.

“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.

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.

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.

Since we will want others to consume this module we need to add it to public_api.ts.

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.

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

Also add the component to public_api.ts

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

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

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.

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:

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.

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

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.

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

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

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

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.

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.

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.

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

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.

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.

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 to learn about more advanced topics regarding the library packaging process.

You can find the code used in the examples in Github here.

Posted on Jun 4 '18 by:

nieds profile

Brenden

@nieds

Software developer in Seattle with a passion for front-end development.

Discussion

markdown guide
 

Looks Simple & Clear!

Having few Questions ..

how to use the library in another angular project without publishing in npm?

 

If you generated the library in the same workspace as the project you want to use you should be able to use it right away (just make sure build the library before the project). If your project is separate from the workspace you are developing your library in you can use the npm link method mentioned above while you are working on the project.

If you need the project to build in a different environment (a build system like travis for example) and don't want to publish to npm you can either

a) publish to a private registry (for example nexus or verdaccio) and point to that
b) build the library and manually include the files in your other Angular project and configure your tsconfig of the project to point to the library similar to the way it's setup when you generate a new library in the same workspace.

// tsconfig.json
{
  "compilerOptions": {
    ...
    "paths": {
      "my-new-library": ["my-new-library"]
    }
  }
}

I haven't tried the second approach so there may be other issues (like maintaining your peer dependencies of the library) that could complicate matters. I generally find it easier to publish to private registries. Another option would be paying for private package hosting on npm.

 

This is awesome! Way to reduce the barrier of entry for OSS and to promote abstraction.