Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use types with dynamic imports?

I'm using dynamic imports with Angular 7 to reduce the size of the initial vendor bundle.

import('xlsx').then(XLSX => {
    const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });
})

But there is an error on the XLSX.WorkBook type saying:

Cannot find namespace XLSX.

XLSX.read works fine.

Question : How do I define types when using dynamic imports?

like image 569
MrVoodoo Avatar asked Jan 16 '19 10:01

MrVoodoo


People also ask

How can I use dynamic import module?

To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module. const module = await import(path) returns a promise that resolves to an object containing the components of the imported module. } = await import(path);

What is the use of dynamic import?

The import() call, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.

Does Dynamic import improve performance?

Dynamic imports, also known as code splitting, refers to the practice of dividing bundles of JavaScript code into smaller chunks, which are then pieced together and loaded into the runtime of an application as a means to drastically boost site performance.

What is a dynamic import TypeScript?

Dynamic import expressions are a new feature and part of ECMAScript that allows users to asynchronously request a module at any arbitrary point in your program. This means that you can conditionally and lazily import other modules and libraries.


1 Answers

XLSX will only represent the value of the import, not the types.

You have two options.

Use an import type:

import('xlsx').then(XLSX => {
    const wb: import('xlsx').WorkBook = XLSX.read(bstr, { type: 'binary' });
})

You can define a type alias to make this easier: type WorkBook = import('xlsx').WorkBook

Import the type:

import { WorkBook } from 'xlsx' // Just for the type, will be elided in this example

import('xlsx').then(XLSX => {
    const wb: WorkBook = XLSX.read(bstr, { type: 'binary' });
})

This second option is more tricky to get right, if you only use the imports from the static import in types, the import statement should be elided (ie not outputted to JS). As soon as you use any import from the static import in an expression (ie. any position that will end up in the JS) the import will not be elided. See more about module being elided

like image 108
Titian Cernicova-Dragomir Avatar answered Oct 20 '22 21:10

Titian Cernicova-Dragomir