Mike5
Mike5

Reputation: 91

Angular 7.x - Can not export class from a custom library

I can't export a class from a custom library and import in the app correctly. Use as type is working, but using with the constructor is not working.

My lib is working... I can use the modules, components, service create from. If I just add a simple exported class, I can not use in the app correctly.

ERROR in ./src/app/demo/demo.component.ts Module not found: Error: Can't resolve 'mylib/lib/global/module1/testClass.class'

this happens if I use in my component the class with contructor...

project/mylib/src/lib/global/module1/testClass.class.ts

export class DemoClass {
    text: string;

    constructor(text:string) {
        this.text = text
    }
}

The lib is correctly compiled without error. In dist

export declare class DemoClass {
    text: string;
    constructor(text: string);
}

public_api.ts

export * from './lib/global/module1/testClass.class';

in ./src/app/demo/demo.component.ts

import { DemoClass } from 'mylib/lib/global/module1/testClass.class';

@Component({
    selector: 'app-demo',
    templateUrl: './demo.component.html',
    styleUrls: ['./demo.component.scss']
})

export class DemoComponent implements OnInit {

    // This will work
    demo: DemoClass = { text: "lorem ipsum" }

    // This will not work and provide error 'Module not found: Error: Can't resolve '
    demo2: DemoClass = new DemoClass('lorem ipsum')

    constructor() { }

    ngOnInit() {

    }
}

edit something probably related is that if I import my class like

{ testClass } from projects/mylib/src/lib/global/module1/testClass.class';

Then it's working. But it's not the correct usage of a custom lib.

I expect to be able to use a class in the app like in the lib.

Upvotes: 2

Views: 2159

Answers (1)

brieucdlf
brieucdlf

Reputation: 181

You have to extend but never try with an external lib but should work :)

Try this

export class DemoComponent extends DemoClass implements OnInit {
  ... 
  constructor(text: string) {
     super(text); // DemoClass constructor params
  }
  ...
}

I see as well that your import is strange. Try it like this

import { DemoClass } from 'mylib/lib/global/module1/testClass';

Upvotes: 1

Related Questions