Issue
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?
Solution
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
Answered By - Titian Cernicova-Dragomir
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.