JavaScript 模块中的循环依赖(ES6)

Cyclic dependencies in JavaScript modules (ES6)

我最近一直在阅读和测试 ES6 模块,并结合使用 2ality 和 MDN 作为我的理解来源。

在我计划现代化的大型遗留 JS 网络应用程序中,我有循环依赖关系,但我没有找到解决问题的方法。 我知道应该尽可能避免循环依赖,迁移后我的下一步将是尽可能地清理。

我的测试用例如下:

test.html:

<script type="module">
    import B from './B.js';

    console.log(B.moo());
</script>

B.js:

// B.js
import A from './A.js';

export default class B {
    static moo() {
        return A.boo();
    }
}

A.js:

// A.js
import B from './B.js';

export default class A extends B {
    static boo() {
        return "Boo";
    }
}

根据以上内容,我基本上只做了两件事:

  1. B.moo()调用静态方法A.boo()
  2. A 扩展 B

但是,上面的代码会导致错误: Uncaught ReferenceError: B is not defined at A.js:3

我知道 ES6 模块是静态解析的,错误是有道理的。但它们也(应该?)支持循环依赖。

经过一番折腾,我找到了一个可行的解决方案。但是我想知道有没有更好的方法?

到目前为止,这是我的工作解决方案:

test.html:

<script type="module">
    import A from './A.js';
    import B from './B.js';

    console.log(B.moo());
</script>

B.js:

import A from './A.js';

export const B = class B {
    static moo() {
        return A.boo();
    }
}

export {B as default};

A.js:

import B from './B.js';

export const A = class A extends B {
    static boo() {
        return "Boo";
    }
}

export {A as default};

经过更多搜索后,我发现了这篇文章:https://medium.com/@rohanjamin/using-scope-to-resolve-circular-dependency-dynamic-loading-issues-in-es6-2ef0244540fa - 不确定为什么我在之前的 Google 搜索中没有遇到它。

它与我正在使用的代码中的代码安排非常相似,而且似乎运行良好。我可以预见到 tree shaking 未来会出现一些问题,但我已经让 Babel 输出了一个循环依赖列表,我们可以在接下来的几个月里手动重构它。