How to get Typescript to compile CommonJS imports?

2k Views Asked by At

I have written a TS file, that loads in a 3rd party package, using import XXX { YYY, ABC, 123 }from 'XXX';

It will compile to CommonJS no issue, and thats OK. But I'd like to compile it to an ESModule. I changed the target and module settings to esnext in my TS config file, and it does compile, however, when I run the file, it errors out saying:

SyntaxError: Named export 'ABC' not found. The requested module 'XXX' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'XXX';
const { ABC } = pkg;

Is there any settings I can use to tell Typescript to convert the imports to the import tye shown in the error message?

1

There are 1 best solutions below

1
Ben On

You may want to try nodenext instead of esnext for the module setting. This is currently experimental but it seems to address your need with CommonJS interop.

I haven't tried it myself so I cannot promise it will work.