1

I have a JavaScript class defined as:

// MyClass.js
module.exports = class MyClass {
  //...
}

This is imported elsewhere as:

// otherModule.js
const MyClass = require('./MyClass');

I'm trying to convert MyClass to TypeScript, so it's now defined as:

// MyClass.ts
class MyClass {
  // ...
}
export default MyClass;

I need to continue to import this using the require syntax in JavaScript files, however do so I need to do either:

// otherModule.js
const MyClass = require('./MyClass').default;
// or
const { default: MyClass } = require('./MyClass');

Is there any way I can avoid having to explicitly specify that I'm importing default? Ideally I'd want to continue importing this with const MyClass = require('./MyClass');, if possible, even if this means I need to change how my TypeScript class is defined/exported.

2
  • Why do you still want to use require? Just use import and let tsc compile to cjs if you want. Commented Apr 14, 2023 at 12:59
  • I dont want to, but I'm trying to refactor a common library that's used by many other repositories. The library will be refactored to TS and will use import/export, but I dont want to have to refactor all the code that imports this and change the way it imports it (that time will come, but way down the line) Commented Apr 14, 2023 at 14:44

1 Answer 1

-1

Set - esModuleInterop to true in your tsconfig https://www.typescriptlang.org/tsconfig#esModuleInterop

{
   esModuleInterop: true
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.