khteh
khteh

Reputation: 3878

Typescript class export from one module and import in another

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.

Upvotes: 0

Views: 2259

Answers (2)

Paramanand Balara
Paramanand Balara

Reputation: 36

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)

Upvotes: 2

liguepk
liguepk

Reputation: 191

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

Upvotes: 1

Related Questions