首页 > 解决方案 > JavaScript 的 ES6 导入如何处理循环依赖?

问题描述

测试.html

<script type="module" src="./B.js"></script>

js

import {bar} from './B.js';
import {test} from './B.js';

export function foo() {
    bar();
}

test();
console.log("IN A");

B.js

import {foo} from './A.js';

export function bar() {
    if (Math.random()) {
        foo();
    }
}

export function test() {
    console.log("test");
}

console.log("IN B");

输出是:

B.js:30 test
A.js:24 IN A
B.js:33 IN B

为什么“In B”是执行的最后一行代码?此外,如果在 test.html, 中src="./A.js",“IN B”是执行的第一行。

标签: javascriptecmascript-6

解决方案


推荐阅读