'How to dynamically import classes?

I've three js files file_a.js , file_b.js & file_c.js, they all have a class called Context:

export class Context{
constructor(){
...
}
Other_functions_which_are_different_for_each_file(){
...
}
}

Based on the argument passed in index.js, I'm calling the Context class from the relevant file.

index.js:

let call = document.currentScript.getAttribute("call");
let {Context} = import('./file'.concat(call));
...
async function app(){
camera = new Context();
}

The problem is index.js doesn't recognise Context as a class. So, I'm getting Context is not a constructor error on the line camera = new Context();.

How can I import the Context class, such that I'm not block scoped & can call the class inside the app() function?



Solution 1:[1]

Dynamic imports return a promise, so you will need to wait for that promise before you can use Context. For example:

const importPromise = import('./file'.concat(call));
...
async function app() {
  const { Context } = await importPromise;
  camera = new Context();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nicholas Tower