Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
140
rated 0 times [  147] [ 7]  / answers: 1 / hits: 12541  / 3 Years ago, fri, july 9, 2021, 12:00:00

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 () {}

More From » webpack

 Answers
10

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.


[#1122] Thursday, July 1, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
collinisaaka

Total Points: 194
Total Questions: 105
Total Answers: 104

Location: Tonga
Member since Tue, Nov 30, 2021
3 Years ago
;