Monday, May 20, 2024
114
rated 0 times [  116] [ 2]  / answers: 1 / hits: 42884  / 8 Years ago, sun, january 15, 2017, 12:00:00

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.


More From » ecmascript-6

 Answers
14

When you have



export default {
bar() {}
}


The actual object exported is of the following form:



exports: {
default: {
bar() {}
}
}


When you do a simple import (e.g., import foo from './foo';) you are actually getting the default object inside the import (i.e., exports.default). This will become apparent when you run babel to compile to ES5.



When you try to import a specific function (e.g., import { bar } from './foo';), as per your case, you are actually trying to get exports.bar instead of exports.default.bar. Hence why the bar function is undefined.



When you have just multiple exports:



export function foo() {};
export function bar() {};


You will end up having this object:



exports: {
foo() {},
bar() {}
}


And thus import { bar } from './foo'; will work. This is the similar case with module.exports you are essentially storing an exports object as above. Hence you can import the bar function.



I hope this is clear enough.


[#59349] Thursday, January 12, 2017, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ramseydeshaunc

Total Points: 30
Total Questions: 91
Total Answers: 103

Location: Palau
Member since Tue, May 30, 2023
1 Year ago
;