In the simple example below im getting the following error :
ReferenceError: Cannot access 'shared' before initialization
but if i change the export default 2 to a function it will work. Why is this behaviour?
index.js
import a from "./testA.js";
export default 2;
testA.js
import shared from "./index.js";
console.log(shared);
export default function () {}
I checked this both with webpack (code transpiled to es5) and with native modules in Chrome. With transpiled code it just logs undefined.
It only gives an error with native modules no matter if the export is a function or number.
This is because, as the error implies, the default export of index.js isn't initialized by the time you're trying to console.log it.
It's equivalent to doing something like:
console.log(a);
const a = 2;
shared will be initialized when 2nd line in index.js is executed, but the execution of index.js stops on line 1 and waits till execution of testA.js is done.
When compiled to es5, there's a different problem because the partially completed module is passed to another, so whatever wasn't initialized by that time ends up as undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With