a blog for those who code

Tuesday 25 May 2021

Creating Local Angular Component Library

This tutorial will see how we can create a local Angular Component Library and use it in another project. Let's say I have two Angular projects, the main project and common project for common UI components. This common UI component will be a library and it will be required in the main project, so we will see how we can create a local Angular library and use it in the main Angular project.

Let's head over to our common UI Project and install the ng-packagr module either locally or globally. The ng-packagr module compiles and packages the angular libraries in Angular Package Format (APF). Once the installation is completed we have to create an ng-package.json file in the same location where package.json is. The contents of the ng-package.json file will be 

{
  "$schema": "./node_modules/ng-packagr/ng-package.schema.json",
  "lib": {
    "entryFile": "src/public_api.ts"   
  }
}

After creating the ng-package.json file we also have to create a public_api.ts file. Using this file we need to export all the modules, enums, components which we have created in our library to use it in another project.

Example of public_api.ts file :

export { MyEnum} from './app/enums';
export { UserData} from './app/modules';
export * from './app/components';

After adding the public_api.ts file, we need to add a command in package.json scripts which will run the package. With the scripts, we can easily run npm run packagr.

"scripts": {
  "packagr": "ng-packagr -p ng-package.json"
}

When we run packagr using the command npm run packagr it will package our code inside the dist folder. Now to use the Angular library in our other project, we have to run npm pack inside the dist folder and head over to the main project and install it using

npm install ../path/common-0.0.0.tgz

Note: The tgz will be created based on the version you provide in the library package.json. Also when you install it will be seen in package.json as

"common": "file:../common/dist/common-0.0.0.tgz"

If you have multiple Angular libraries it's better to change it to the full path, because when you install it in another library and if that is installed again then this path will not work.

Now after doing this we will have our local angular component library which we can use it in any project. If we are changing anything in the library, then we need to run these commands again and install the library again to get the lastest changes.

No comments:

Post a Comment