Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceError: Cannot access before initialization circular dependency

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 () {}
like image 356
Nick Avatar asked Oct 27 '25 13:10

Nick


1 Answers

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.

like image 199
marzelin Avatar answered Oct 30 '25 01:10

marzelin