Search code examples
node.jstypescriptimportexportcommonjs

How to export a TypeScript module so that can be imported both from TypeScript and Node?


Let's say a have the following TypeScript module:

function foo () {
  return 123;
}

//TODO: Export code here

I want to export it in such a way that can be imported in these ways from TypeScript:

import foo from 'foo';
import * as foo from 'foo';

and in this way from Node:

const foo = require ( 'foo' );

Requirements:

  • I don't what the users of my module to have to set the allowSyntheticDefaultImports option
  • I want the code for exporting the module to be as clean as possible
  • I want to preserve type definitions

So far I've come up with the following "solutions", but they either don't preserve type definitions well enough or are too verbose:

export = foo['default'] = foo as typeof foo & { default: typeof foo };
export = foo['default'] = foo;

Is there a better way?


Solution

  • This is the best that I could come up with:

    export = Object.assign ( foo, { default: foo } );
    

    It's pretty terse, type definitions are properly generated, and it can be imported using all the aforementioned methods.