TheUnreal
TheUnreal

Reputation: 24492

Angular CLI - 'Cannot find module' when using custom library created with 'ng new library'

I'm trying to consume my own library after creating it with the Angular CLI using ng new library lib-name.

I'm trying to import the library as documented, this way:

import {MyLibModule} from 'ngx-mylib';

But I get the following error:

 error TS2307: Cannot find module 'ngx-mylib'.

I did ng build ngx-mylib and also verified my tsconfig.json has the following paths (which are added automatically using the CLI):

"paths": {
      "ngx-mylib": [
        "dist/ngx-chartjs"
      ],
      "ngx-mylib/*": [
        "dist/ngx-chartjs/*"
      ]
    }

public-api.ts:

export * from './lib/charts.service';
export * from './lib/chart.component';
export * from './lib/charts.module';

What I'm missing?

Upvotes: 14

Views: 11709

Answers (4)

Emeric
Emeric

Reputation: 6925

For me (Angular 14) I had to add the paths in the tsconfig.app.json too.


First check that your tsconfig.json contains the following:

{
  "compilerOptions": {
    "paths": {
      "my-lib": [
        "dist/my-lib"
      ],
      "my-lib/*": [
        "dist/my-lib/*"
      ]
    }
  }
}

This should be generated automatically when creating your lib (using ng generate library my-lib).

Now what I had to add is the following in src/tsconfig.app.json:

{
  "compilerOptions": {
    "paths": {
      "my-lib": [
        "../dist/my-lib"
      ],
      "my-lib/*": [
        "../dist/my-lib/*"
      ]
    }
  }
}

You should now be able to import your lib using import { MyLibModule } from 'my-lib';.

Upvotes: 2

Jules
Jules

Reputation: 115

Try adding MyLibModule to your app.module imports and exports.

Upvotes: 0

Khashayar Pakkhesal
Khashayar Pakkhesal

Reputation: 434

try to build it again and then run your project sometimes angular can't build the library properly

Upvotes: 0

José Matos
José Matos

Reputation: 1

After build your library you have to pack it.

Go to your dist folder and run

npm pack

this will create a your-lib-name.tgz file and then you can use it on your projects.

Use it like this:

npm install path-to-your-tgz-file/your-lib.tgz

You can also publish it to npm or to a private repository.

Upvotes: 2

Related Questions