如何在动态导入中使用类型? [英] How to use types with dynamic imports?

查看:106
本文介绍了如何在动态导入中使用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将动态导入与Angular 7结合使用,以减小初始供应商捆绑包的大小.

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' });
})

但是 XLSX.WorkBook 类型上出现错误,提示找不到命名空间XLSX".
XLSX.read可以正常工作.

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?

推荐答案

XLSX 仅表示导入的值,而不表示类型.

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

您有两个选择.

使用导入类型:

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

您可以定义类型别名来简化此操作: type WorkBook = import('xlsx').WorkBook

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

导入类型:

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' });
})

第二种选择比较棘手,如果仅使用静态导入类型中的导入,则应该省略import语句(即不输出到JS).一旦您在表达式中使用了静态导入中的任何导入(即,将在JS中结束的任何位置),导入就不会被忽略.查看有关被删除的模块的更多信息

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

这篇关于如何在动态导入中使用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆