I need some help to get how some function export works inside JS.
Let’s say I have this code
function goodbuy() {
console.log('bye');
}
function myModule() {
function hello() {
console.log('Hello');
}
hello();
}
export {goodbuy};
export default myModule;
If I call it:
import {goodbuy} from "./main";
import hello from "./main";
goodbuy();
hello();
The output is:
bye
Hello
But if I remove hello()
call from function myModule()
it does not work.
function myModule() {
function hello() {
console.log('Hello');
}
}
with output:
bye
It is a little bit strange for me, as I did not import myModule() where this hello() is called.
PyCharm and VS Code does not show function hello() is not reachable, seems I can export it, but can’t use without calling inside the main function myModule().
Could somebody please explain how it works?
I would like an explanation why this function can work with calling inside the main function and can’t work without it.
2
Answers
When you do:
You are importing the
default export
from the other file, which ismyModule
, due to this line:You could actually replace that
import
with any other name:They are all importing the
default export
from that file.This is not the same as importing the
hello
function defined inside themyModule
function. If you want that, you should probably use named exports and write something like this:The only reason you see
Hello
in the first case is becase:myModule
(now aliases ashello
).myModule
(ashello()
).myModule
internally calls thehello
function
defined within itself.** return hellow() from myModule**
** And called hellow function like myModule()()**