https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Is it possible in Typescript to dynamically set the from path into a variable when importing?
Eg turn this:
import {HomeComponent} from './dashboard/home/home.component';
To something like this:
let hompageComponentPath = './dashboard/home/home.component';
import * from hompageComponentPath;
import
proposalThere is a proposal for dynamic import in ECMAScript.
Since TypeScript 2.4, dynamic import
expressions are available. Here is an example:
async function getZipFile(name: string, files: File[]): Promise<File> {
const zipUtil = await import('./utils/create-zip-file');
const zipContents = await zipUtil.getAsBlob(files);
return new File(zipContents, name);
}
The import
, used as a function, returns a promise which can be awaited.
import
/ export
It's not possible to do that with the syntax import
/ export
because the ES6 standard had explicitly defined modules in a static way.
From the article ES6 In Depth: Modules:
For a dynamic language, JavaScript has gotten itself a surprisingly static module system.
- All flavors of
import
andexport
are allowed only at toplevel in a module. There are no conditional imports or exports, and you can’t useimport
in function scope.- All exported identifiers must be explicitly exported by name in the source code. You can’t programmatically loop through an array and export a bunch of names in a data-driven way.
- Module objects are frozen. There is no way to hack a new feature into a module object, polyfill style.
- All of a module’s dependencies must be loaded, parsed, and linked eagerly, before any module code runs. There’s no syntax for an
import
that can be loaded lazily, on demand.- There is no error recovery for
import
errors. An app may have hundreds of modules in it, and if anything fails to load or link, nothing runs. You can’t import in atry/catch
block. (The upside here is that because the system is so static, webpack can detect those errors for you at compile time.)- There is no hook allowing a module to run some code before its dependencies load. This means that modules have no control over how their dependencies are loaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With