简体   繁体   中英

Cyclic dependencies in JavaScript modules (ES6)

I've been reading and testing ES6 modules recently and have used a combination of 2ality and MDN as my source of understanding.

In a large legacy JS web-app that I'm planning to modernise I have circular dependencies and I have found no solution on how to resolve my problem. I know that circular dependencies should be avoided as much as possible and my next step after migration will be to clear up as much as I can.

My test case is as follows:

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";
    }
}

From the above, I essentially have just 2 things going on:

  1. B.moo() calls the static method A.boo()
  2. A extends B

However, the above code results in an error: Uncaught ReferenceError: B is not defined at A.js:3

I get that ES6 modules are resolved statically and the error makes sense. But they're also ( supposed? ) to support cyclic dependencies.

After much messing around I have found a solution that works. But I'm wondering if there's a better way?

Here is my working solution so far:

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};

After some more searching I came across this article: https://medium.com/@rohanjamin/using-scope-to-resolve-circular-dependency-dynamic-loading-issues-in-es6-2ef0244540fa - not sure why I didn't come across it on my previous Google searches.

It rather closely resembles the same code arrangement I have in the code I'm working with and it seems to be working well. I can foresee that there will be some future issues with tree shaking but I've got Babel to output a list of circular dependencies that we can manually refactor over the next few months.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM