1

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?

Mr Pablo
  • 4,109
  • 8
  • 51
  • 104
  • No. The error message tells you to change your code (use `XXX.ABC`) not to change the compiler configuration. – Bergi Mar 01 '22 at 13:20
  • 1
    The proper alternative would be to get the third party provide their package as an ES6 module. – Bergi Mar 01 '22 at 13:21
  • @Bergi yes, tat would be the ideal solution, but it's unlikely to hapen any time soon :( – Mr Pablo Mar 01 '22 at 13:48
  • …and if you can't make them do that, you can either do it yourselves (forking the lib) or make an adapter module that imports their commonjs module and provides named exports in your favourite ES6 style – Bergi Mar 01 '22 at 13:57
  • For the later suggestion, what would that look like potentially? – Mr Pablo Mar 01 '22 at 14:43

1 Answers1

0

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.

Ben
  • 1,331
  • 2
  • 8
  • 15
  • Thank you for the suggestion, but I'd prefer to stick with stable builds of Typescript. Seems I probably just ned to refactor my code as shown. – Mr Pablo Mar 01 '22 at 11:38