Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a local library in Angular?

While I was creating an Angular application I wanted to build a library where I can put components which can be useful even in other projects. In order to create the library I've made another Angular workspace where I've generated the library project and used the application project generated automatically within the workspace to show individual components.

ng new my-components-library
cd my-components-library
ng generate library components-library

Now I have a library with working components which pass the unit tests and works properly in the attached application project but I need them in my project's workspace. I tried to include the library on this way.

Inside my project workspace

npm install ../my-components-library/projects/components-library

the command run properly and I get a reference to the library into the host project's package.json but when I have to include modules from the external library in a project's module using import {myModule} from 'components-library' I get an error because Angular can't find the module.

like image 600
Emiliano S. Avatar asked Oct 14 '19 09:10

Emiliano S.


2 Answers

You can either use npm link, which creates a symlink in your host apps node_modules directory.

  • Run npm link in the local library
  • Run npm link @local-library-name in the host application
  • But make sure you make the following changes on your host applications angular.json file. If you are using less angular 11 or lower, then add "preserveSymlinks": true else sourceMap with scripts, styles, vendor as true
    "build": {
      "options": {
        "preserveSymlinks": true, // angular 11 or less
      }
    }, 
{
  "projects": {
    "your-app": {
      "architect": {
        "build": {
          "options": {
            "sourceMap": {     // angular 12 or more
              "scripts": true,
              "styles": true,
              "vendor": true
            },

You can package the library into tar using npm pack.

  • Run npm pack in your library
  • Run npm i your-library-path.tgz in your host application
  • Or you can update the package.json with new dependency of the host application and run npm i
"your-library-name": "file:your-library-path.tgz",
like image 186
deepakchethan Avatar answered Sep 21 '22 11:09

deepakchethan


Need to register in angular.json

"scripts": ["src/assets/scripts/yourComponentLibrary.js"]

In you component where you want to use the library, need to declare as a const above @Component({...

declare const YourComponentLibraryName: any;

like image 26
razvanstan Avatar answered Sep 23 '22 11:09

razvanstan