Search code examples
typescriptecmascript-5

Can I import function that exported by ES5 in the {...}


I have an ES5 module that exports a simple function like this

var sum = function(a, b) {
  return a + b;
}

module.exports = sum;
module.exports.default = sum;

I have a typescript module that imports the sum function, but it only works if I import it outside the {...} or put 'default as sum' keyword if I want to put it inside {...} like so

// This works
import sum from './sum';

// This works too
// import { default as sum } from './sum'; 

// This doesn't work (I want this to work but don't know how)
// import { sum } from './sum'; 

console.log(sum(1, 2));

Is there any way (maybe change the ES5 module) so I can import it like { sum } and it would work? Any suggestion is more than welcome.

See the code in action in Stackblitz: https://stackblitz.com/edit/import-es5-export-function-using-brackets


Solution

  • all you had to do was use module.exports like this:

    module.exports = {sum}
    

    here it is working