Creating UI components library with Angular
Feeling a need to create re-usable UI components for all of your projects or for all the projects across your organization? Here’s a quick guide to creating such a library with angular and for angular apps and finally publish it to npm.
- Identify the common components which can be a part of your library.
- Create an angular workspace using
ng new <project-name> --createApplication=false.
--createApplication=falseflag will provide an angular workspace without any app inside it.
- Create a library inside your angular workspace.
ng g library <lib-name>
- This will be the lib where all your lib components will go.
- Now, we need an application to test our lib and for local development of lib components.
- So, create an app using
ng g application <app-name>
- That’s all the dev setup needed for a basic
These are the steps to build and publish to npm manually. Based on your CI-CD tool you may automate them.
- cd into your lib
- Bump up the semver version using
npm version patchor
npm version minoror
npm version major.
- Good to have a npm script for the first 2 steps.
- cd back into workspace root and build the library using
ng build <lib-name>.
- This will create a dist folder with packaged lib.
- cd into
cd dist/<lib-name>and run
npm publish. (offcourse, first you need to be logged in to npm).
- That’s all folks! Your lib is now published on npm.
encapsulation: ViewEncapsulation.Noneas suggested here is one of the common way to include global styles.
Since the theme.min.css is now a part of lib so the user can simple import this file from their node_modules folder. It’s preferred to add this file in angular.json’s
Similarly you can export global js and import it from node_modules into angular.json’s
This is a bit tricky and need to follow specific guidelines.
I prefer copying them using cpx and then in the app copy them again from node_modules folder to
assets/* or any folder having similar path as it is there in lib code.
Feel free to add your suggestions and feedback in the comments below.
- Ayush 🙂