Search code examples
javascriptes6-modules

Module import export issue


I am trying to export a module, extend and export it in another module and then import it back in the original module in order to use it, like this:

// base-class.js
export class BaseClass {}

import { ExtendedBaseClass } from './extended-base-class.mjs';

console.log(ExtendedBaseClass);
// extended-base-class.js
import { BaseClass } from './base-class.mjs';

export class ExtendedBaseClass extends BaseClass {}

However it fails with an error:

ReferenceError: Cannot access 'BaseClass' before initialization, at extended-base-class.js:3:40

Based on my understanding of the order of operations this seem illogical, so what is the issue and how can I solve it?

For context: My current solution is to put just everything into the same file, but I want to move it into separate files, as my real classes are quite lengthy and thus I want to split it apart.


Solution

  • ES6 modules always resolves their imports first before executing their body. So, in your case, base class will first try to import extended base class, even before exporting the base class from itself. Since extended base class tries to import base class first, it is not yet initialized at this point and hence you get the error.

    What you can do is to move base class and extended base class to two separate files and then use a third file to import the extended base class

    // base.js

    export class BaseClass {}
    

    // extended

    import { BaseClass } from './base.js';
    export class ExtendedBaseClass extends BaseClass {}
    

    // index

    import { ExtendedBaseClass } from './extended.js';
    console.log(ExtendedBaseClass);
    

    Alternatively, if you use CJS module system, your approach will work since the require statement which we use in CJS (equivalent of import here) works just similar to a normal function call. So it will only execute when the execution reaches that line. However it is very highly discouraged to have such circular dependencies since it could easily convolute the codebase