Home > Back-end >  Typescript class export from one module and import in another
Typescript class export from one module and import in another

Time:08-09

I have the following source tree:

/project/
  |- src/
      |- moduleA
          |- index.ts
          |- classA.ts (with a public function doSomething())
      |- moduleB
          |- classB.ts

moduleA index.ts:

export * from './classA'

moduleA classA.ts:

export default class ClassA {
    public doSomething(req: Request, res: Response, next: NextFunction) {
    }
}

and moduleB tries to import classA in order to use doSomething():

import {classA} from 'moduleA'

Error when npm run build in moduleB:

routes/api.ts:2:10 - error TS2305: Module '"moduleA"' has no exported member 'ClassA'.

2 import { ClassA } from 'moduleA';
           ~~~~~~~~~

What do I miss? Thanks.

CodePudding user response:

It's because you're declaring classA as default. When you do so, the import should look like import ClassA from 'moduleA'.

Please check this post if you want more information

Typescript export vs. default export

CodePudding user response:

Please export class without default keyword. try this

export class ClassA {
public doSomething(req: Request, res: Response, next: NextFunction) {
}

}

then import import { ClassA } from 'moduleA';

var classA = new ClassA(); (or you can use it by injecting ClassA) if you want to use method of ClassA

classA.doSomething(req, res, next)

  • Related