Is it possible to import parent module from sub class in JavaScript?

Viewed 150

I have two files with their own modules, Sub.js and Parent.js

Parent.js:

import Sub from "/.Sub.js"
export default class Parent {
    static createSomething(){
        new Sub();
    }
}

Sub.js:

import Parent from "/.Parent.js"
export default class Sub extends Parent {
    contructor(){}
}

With that I get error:

ReferenceError: can't access lexical declaration`X' before initialization

Sub-module cannot be used because Parent-module is needed, but importing Parent-module requires importing Sub-module, I think?

This could be resolved by putting them in the same file, but I wonder if there is a way of keeping them as seperates files.

1 Answers

When implementing such circular dependencies, make sure that the file you're using in other code doesn't contain top-level export declarations that require the other file. In your case:

  • If you import Sub in some other file, its top-level export requires Parent which requires Sub, then it's impossible to resolve: the snake bites its own tail
  • If you import Parent in some other file, its top-level export doesn't need Sub immediately (only when createSomething is being called). In that case, the Parent export fully resolves, then the Sub file is able to resolve its own export as well.
Related