The potential of the dynamic import
feature
An intriguing proposal for dynamic importing in ECMAScript can be found here.
Starting from TypeScript 2.4, developers have access to dynamic import
expressions, as shown below:
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);
}
When used as a function, the import
keyword returns a promise that can be awaited.
... Contrasting with ES6 static import
/ export
The limitations of using the ES6 syntax for modules are highlighted by the inability to achieve dynamic imports due to its inherently static nature.
As explained in the article ES6 In Depth: Modules:
In comparison to its dynamic counterparts, JavaScript's module system is surprisingly rigid and static.
- Imports and exports must occur at the top level of a module, without conditional constructs or within function scopes.
- All exported identifiers need to be explicitly declared in the source code, preventing programmatically exporting names based on data.
- Module objects are immutable, disallowing modifications post-definition.
- All dependencies must be loaded upfront before any module execution, lacking lazy loading capabilities.
- No error handling mechanism is present for import failures, potentially halting an application if any module encounters an issue during loading.
- Modules lack pre-loading hooks, limiting control over dependency loading processes.