ReferenceError: Cannot access before initialization circular dependency
ReferenceError: Cannot access before initialization circular dependency
在下面的简单示例中,我收到以下错误:
ReferenceError: Cannot access 'shared' before initialization
但是如果我将 export default 2 更改为一个函数,它将起作用。为什么会出现这种行为?
index.js
import a from "./testA.js";
export default 2;
testA.js
import shared from "./index.js";
console.log(shared);
export default function () {}
我用 webpack(代码转换为 es5)和 Chrome 中的本机模块检查了这一点。使用转译后的代码,它只记录 undefined
。
无论导出的是函数还是数字,它只会对本机模块产生错误。
这是因为,如错误所示,index.js
的 default
导出在您尝试 console.log
时尚未初始化。
这相当于做这样的事情:
console.log(a);
const a = 2;
shared
将在 index.js
中的第 2 行执行时初始化,但 index.js
的执行在第 1 行停止并等待 testA.js
的执行完成.
当编译为 es5 时,有一个不同的问题,因为部分完成的模块被传递给另一个模块,所以到那时没有初始化的任何东西最终都会成为 undefined
。
在下面的简单示例中,我收到以下错误:
ReferenceError: Cannot access 'shared' before initialization
但是如果我将 export default 2 更改为一个函数,它将起作用。为什么会出现这种行为?
index.js
import a from "./testA.js";
export default 2;
testA.js
import shared from "./index.js";
console.log(shared);
export default function () {}
我用 webpack(代码转换为 es5)和 Chrome 中的本机模块检查了这一点。使用转译后的代码,它只记录 undefined
。
无论导出的是函数还是数字,它只会对本机模块产生错误。
这是因为,如错误所示,index.js
的 default
导出在您尝试 console.log
时尚未初始化。
这相当于做这样的事情:
console.log(a);
const a = 2;
shared
将在 index.js
中的第 2 行执行时初始化,但 index.js
的执行在第 1 行停止并等待 testA.js
的执行完成.
当编译为 es5 时,有一个不同的问题,因为部分完成的模块被传递给另一个模块,所以到那时没有初始化的任何东西最终都会成为 undefined
。