'export default vs module.exports differences

This works:

import {bar} from './foo';
bar();

// foo.js
module.exports = {
 bar() {}
}

And this works:

import foo from './foo';
foo.bar();

// foo.js
export default {
 bar() {}
}

So why doesn't this work?

import {bar} from './foo';
bar();

// foo.js
export default {
 bar() {}
}

It throws TypeError: (0 , _foo.bar) is not a function.



Solution 1:[1]

curly bracket imports {} are only for named exports. for default export you are not expected to use them during import. if you want still use {} for your 3rd case this should work.

import {default as bar } from './foo';
bar();

// foo.js
export default {
  bar() {}
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1