Home > Net >  javascript not a constructor exception while creating objects in node_modules
javascript not a constructor exception while creating objects in node_modules

Time:09-22

I am facing any issue in react. Here How I am defining the class BackendServiceClient

class BackendServiceClient {
  private readonly source: string;

constructor(source?: string) {
    if (source) {
      this.source = source;
    }
    axios.defaults.headers = this.setDefaultHeaders();
  }
}
.... some logic

export default BackendServiceClient;

This how the BackendServiceClient is export in index.ts in common library in this class we export all the vars that could be used by clients of the library

export { default as BackendServiceClient} from './api/BackendServiceClient';

While building this commons library into my application I got error commons.BackendServiceClient is not constructor

and when checked the line causing errors from file in node modules


backendServiceClient: /*#__PURE__*/new commons.BackendServiceClient(),

Does someone have faced this issue ? Thanks

CodePudding user response:

Since you export BackendServiceClient from BackendServiceClient.ts, when you want to use it in another file (let's say index.ts) you need to import it and then export it.

import BackendServiceClient from './api/BackendServiceClient';

And use it -

let backend = new BackendServiceClient();

Only then, export it -

export const client = {
    backend: backend
}

CodePudding user response:

After replicating your setup locally, you may want to ensure that you're importing commons correctly.

The solution that worked for me:

import * as commons from './<path_to_common_lib>';
new commons.BackendServiceClient();

If this doesn't help, verify your common library is not overwriting BackendServiceClient to something that's not a constructor.

(used TypeScript 4.8.3 and [email protected], all default settings)

  • Related