Alex Gusev
Alex Gusev

Reputation: 1854

Deferred export in EcmaScript modules (JavaScript)

Is it possible to perform deferred export in EcmaScript modules (after executing some async operations in importing script, for example)?

function do_export() {
    export default class AsyncClass {
        constructor() {
            this.name = "Async Class";
        }
    }
}

setTimeout(do_export, 500);

Upvotes: 1

Views: 569

Answers (1)

Tomáš Zato
Tomáš Zato

Reputation: 53183

Not like this, both import and export are expected to evaluate in one go. Export can never be invoked later. Think about it this way: what should happen if do_export is called a second time?

However import can be used as a function:

const promise = import("module-name");
const module_name = await promise;

Which means you can defer import of your module until it's needed.

An alternative to deferring export, as you wanted to, is to return Promise, that's what promises are for:

export default new Promise((resolve) => {
  setTimeout(()=>{
    class AsyncClass {
      constructor() {
        this.name = "Async Class";
      }
    }
    resolve(AsyncClass);
  }, 500);
});

Now you can import the module immediately, but have to await on the value in your program:

import AsyncClass from "./AsyncClass.js";


(async ()=>{
    const instance = new (await AsyncClass)();
    console.log(instance.name);
})();

Upvotes: 1

Related Questions