Search code examples
javascriptnode.jstypescriptcommonjses6-modules

Support ES6 module syntax along with CommonJS


So I have this simple module:

export default function(){}

if I don't use export default, then the TypeScript compiler will write one warning saying my "module has no default export", which I'd like to avoid.

So to use this module, we would do:

import fn from 'my-module';

that's all good and well, but what if I want to use CommonJS to import it?

Then I have to do this:

const fn = require('my-module').default;

This is pretty awkward for users. Is there any way around this?


Solution

  • There are equivalent:

    import tscmultiwatch from 'tsc-multi-watch';
    const {default:tscmultiwatch} = require('tsc-multi-watch'); 
    

    That way you can avoid the less pleasant:

    const tscmultiwatch = require('tsc-multi-watch').default; 
    

    And tsc-multi-watch might look like

    export default function(){
    
    }