How to allow CommonJS programs to import from my TypeScript library without using require().default and having autocomplete in text editors

Viewed 78

I'm currently developing a TypeScript library to be used internally in my company's projects, which are a mix of JavaScript and TypeScript Node applications.

So, I want to be able to import the library's default class properly in JavaScript with CommonJS. However, I can only use my class in these programs if I import it with require('...').default.

I managed to make it work previously by adding a module.exports = MyClass at the end of the file, but the autocomplete of VSCode doesn't seem to catch up to that, still suggesting the default before showing the methods.

How can I make it so I can import my class by just using require('...') while still making sure the autocomplete is properly working?

Thanks.

EDIT:

For clarity, what I want to do is to be able to do this:

const MyClass = require('MyTypeScriptClass');

instead of:

const MyClass = require('MyTypeScriptClass').default;

Edit

I decided to not use export default when exporting from a library, since it seems to be what every other library does.

1 Answers

The TypeScript equivalent should be this:

class MyClass {
}

export = MyClass

Can also be inlined to export = class MyClass { ... if that is preferred.

(To import an export like this in a TypeScript project you need to set the esModuleInterop flag.)

Related