Even though using import
may seem similar to destructuring assignment on the surface, it is actually quite different. Importing does not encompass all the functionalities of destructuring assignment. It has its own unique features such as renaming, default imports, and importing a module namespace object. Therefore, you cannot directly import dynamicImportations.ExampleClass
through an import
statement. Instead, you must import dynamicImportations
and then extract the property from it.
You have a few options:
Continue with your current approach
or
Utilize post-import destructuring:
import { dynamicImportations } from 'exampleA.ts';
const { ExampleClass } = dynamicImportations;
const exampleClass = new ExampleClass();
Import the module namespace object and destructure it afterwards; however, this method is not significantly different from #2.
While I do not necessarily suggest this, option #3 can be achieved in a single statement if dynamic import
is supported in your environment along with top-level await
(a Stage 3 proposal):
const {dynamicImportations: { ExampleClass }} = await import("exampleA.ts");
const exampleClass = new ExampleClass();
It's worth noting that this dynamic approach is essentially equivalent to:
const * as temp from "exampleA.ts";
const {dynamicImportations: { ExampleClass }} = temp;
const exampleClass = new ExampleClass();
Additionally, keep in mind that dynamic import
could potentially hinder tree-shaking your code for bundlers or the JavaScript engine itself.