typescriptwrappercommonjs

How to make default export compatible with CommonJS


I am currently in the process of writing a wrapper for an API in TypeScript but am currently experiencing an issue when trying to use said wrapper in CommonJS after its built.

I have a class located in BattleMetrics.ts;

export default class BattleMetrics {
    private axios: any;
    constructor(token: string) {
      ....
    }
}

That class is then imported into the main file, and exported as default as well;

import BattleMetrics from './src/BattleMetrics';

export default BattleMetrics;

However, once built if I make for instance a test.js file and write something along the lines of

const BattleMetrics = require('../../dist/index.js')

const bm = new BattleMetrics('123')

I will get the error TypeError: BattleMetrics is not a constructor

however if I do the same test in typescript it works fine. In CommonJS I need to use bm = new BattleMetrics.default() in order for it to work, but I really would rather avoid that.

If I edit the compiled index.js adding "modules" infront of the .export it works as expected.

How can I resolve this so that when requiring the base file will work both in commonJS and TypeScript

Changed the type of exporting within tsconfig, etc no resolution found.


Solution

  • You can modify your main file to export it as a default export like this

    // main.ts
    import BattleMetricsClass from './src/BattleMetrics';
    
    export { BattleMetricsClass as BattleMetrics };
    

    This ensures TypeScript to transpile the code, it exports the default export as a named export which becomes compatible with CommonJS

    When you import BattleMetics you should be able to use it without the .default()

    // test.ts
    const { BattleMetrics } = require('../../dist/index.js');
    
    const bm = new BattleMetrics('123');