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.
Development Setup
- 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.cd <project-name>- 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
hello worldcomponent.
Deployment Guidelines
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
cd projects/<lib-name>/ - Bump up the semver version using
npm version patchornpm version minorornpm 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 runnpm publish. (offcourse, first you need to be logged in to npm). - That’s all folks! Your lib is now published on npm.
Bonus Material
Including global styles
-
Using
encapsulation: ViewEncapsulation.Noneas suggested here is one of the common way to include global styles. -
I had a theme folder with around 15 different SCSS files, so I have used parcel bundler to create a single minified bundle and then use cpx to copy that style to dist as part of build step.
-
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
styles: [] -
Similarly you can export global js and import it from node_modules into angular.json’s
scripts: []
Serving static assets
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 🙂