John John - 1 year ago 190
TypeScript Question

typescript import from <variable> instead of literal string?

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;

Answer Source

No, it's not possible 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 and export are allowed only at toplevel in a module. There are no conditional imports or exports, and you can’t use import 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 a try/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.

There is a project of "module loader API", that will provide a way to dynamically load modules. But not standardized. See the book of Dr. Axel Rauschmayer:

The module loader API is work in progress

As you can see in the repository of the JavaScript Loader Standard, the module loader API is still work in progress. Everything you read about it in this book is tentative. To get an impression of what the API may look like, you can take a look at the ES6 Module Loader Polyfill on GitHub.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download