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.
ng new <project-name> --createApplication=false
.--createApplication=false
flag will provide an angular workspace without any app inside it.cd <project-name>
ng g library <lib-name>
ng g application <app-name>
hello world
component.These are the steps to build and publish to npm manually. Based on your CI-CD tool you may automate them.
cd projects/<lib-name>/
npm version patch
or npm version minor
or npm version major
.ng build <lib-name>
.cd dist/<lib-name>
and run npm publish
. (offcourse, first you need to be logged in to npm).Using encapsulation: ViewEncapsulation.None
as 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: []
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 🙂