How to use types with dynamic imports?

若如初见. 提交于 2021-02-07 19:14:42

问题


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?


回答1:


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




回答2:


I don't know your context, so I suppose two things:

  1. You defined a XLSX type elsewhere, but the XLSX parameter variable is shadowing the external variable. To avoid shadowing, just use another name for the parameter variable (for example prepending an underscore):

    import('xlsx').then(_XLSX => {
        const wb: XLSX.WorkBook = _XLSX.read(bstr, { type: 'binary' });
    })
    
  2. You think that XLSX.WorkBook is a type, but it's not! XLSX is a javascript library, and javascript doesn't have a concept of type. Also when using TypeScript, it's then get transpilled to javascript and any information about type gets lost. There is no a solution for this problem, but probably you have to import the type from somewhere else, for example DefinetelyTyped. Just import the type in your component then you'll be able to use it.



来源:https://stackoverflow.com/questions/54214910/how-to-use-types-with-dynamic-imports

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!