Creating Local Angular Module and Using It In Another Project

in Programming/Dev2 months ago

Recently we have started a new project where we will be creating 3 projects all together in Angular.

  1. The Main Angular Project
  2. A Common Project for Common UI Components
  3. A Login Project

image.png
PC: Pixabay.com

Now login project will be requiring common UI components and our main angular project will be using both common project and login project. So let's say you have all the three project ready with you.

Let's head over to our Common UI Project. Then we will be installing ng-packagr module either locally or globally doesn't matter. The ng-packagr module compiles and packages the angular libraries in Angular Package Format (APF). Once done we will be creating a ng-package.json in the same place where my package.json is

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

You should then defined a public_api.ts inside a src file and then export all the modules, enums, component which you want to use in the other project.

After doing it I just added the command in scripts to run the ng packagr.

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

Once we do ng run packagr it will package our code inside the dist folder. Now to use it in our other project, we have to run npm pack inside the dist folder and head over to other 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"

Change it to the full path, as because when you install it in another library and if that is installed again then this path will not work.

The same steps we have to follow for our login project too and thus at last we have to install both the project in our main Angular Project.

In the main Angular project we need not have to change the file:../ to full path that is only necessary for my common project as it was being used by login and thus login is used by the main and that's why it was needed.

Sort: