DEV Community

Don
Don

Posted on

Using npm link in Angular9+

When building an Angular library, 'npm link' can shorten the feedback loop between the library and the application. However, if you simply build the library and link it, it will throw errors when the project starts.This is because the application is compiled in Ivy mode, so its dependencies i.e. the linked library, should be compiled in Ivy mode too.

Here is a solution:

  1. Create a new tsconfig.lib.ivy.json in project/PROJECT_NAME with the following setting. This ensures that Ivy view engine is used to compile the project whereas the library build does not use Ivy.
{
  "extends": "./tsconfig.lib.json",
  "angularCompilerOptions": {
    "enableIvy": true
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. In the library's angular.json, add a new configuration ivy under project->PROJECT_NAME->architect->build.
...
"configurations": {
  "production": {
    "tsConfig": "projects/PROJECT_NAME/tsconfig.lib.prod.json"
  },
  "ivy": {
    "tsConfig": "projects/PROJECT_NAME/tsconfig.lib.ivy.json"
  }
}
Enter fullscreen mode Exit fullscreen mode
  1. Update your package.json for easy access to the following commands:
 "scripts": {
    ...
    "build:ivy": "ng build PROJECT_NAME --configuration=ivy"
  }
Enter fullscreen mode Exit fullscreen mode
  1. Run npm run build:ivy. This will build an Ivy-compatible library.

  2. Run cd dist/PROJECT_NAME

  3. Run npm link

  4. In the project, run npm link LIBRARY_NAME to link to the library.

Now the library is linked to the project.

Bonus tip: Run npm run build:ivy -- --watch so that the library gets rebuilt on every code change.

Top comments (0)