简体   繁体   English

如何在Typescript中将import语句与import all语句组合?

[英]How to combine import statements with an import all statement in Typescript?

I've the following import statements using Typescript: 我有以下使用Typescript的import语句:

import * as React from 'react';
import { MouseEvent } from 'react'

Typescript complains that I should combine these multiple imports. Typescript抱怨我应该合并这些多个导入。 I've tried the following, but that MouseEvent being imported is different: 我尝试了以下操作,但是导入的MouseEvent是不同的:

import MouseEvent, * as React from 'react'

In this combined import statement, the MouseEvent is different from the one imported through import { MouseEvent } from 'react' . 在此组合的import语句中, MouseEvent与通过import { MouseEvent } from 'react'不同。

For some reason, Typescript recognises that the MouseEvent in import { MouseEvent } from 'react' accepts type generics but the MouseEvent in import MouseEvent, * as React from 'react' doesn't. 出于某种原因,打字稿认识到MouseEventimport { MouseEvent } from 'react'接受类型仿制药,但MouseEventimport MouseEvent, * as React from 'react'不。

How can I combine the import statements while still keeping the MouseEvent which has generics? 我如何合并导入语句,同时又保留具有泛型的MouseEvent

TypeScript cannot complain about these import statements because they are correct. TypeScript不能抱怨这些导入语句,因为它们是正确的。 It is TSLint that can complain about them and cause an error. TSLint可以抱怨它们并导致错误。

There's no way to shorten them to one line. 无法将它们缩短为一行。 A common way to do this is to use default export that React also provides: 一种常见的方法是使用React还提供的默认导出:

import React, { MouseEvent } from 'react'

A downside is that the package is imported entirely into the bundle and cannot make use of tree shaking. 不利的一面是,该包装已完全导入捆绑包中,无法利用摇树的作用。

A safe way to do this is: 一种安全的方法是:

import * as React from 'react';
import { MouseEvent } from 'react'

In case this causes TSLint error, respective rule needs to be disabled. 如果这会导致TSLint错误,则需要禁用相应的规则。

When you're using import * as React from 'react' , you import the whole module into a single variable called React . 当您使用import * as React from 'react' ,您会将整个模块导入一个名为React变量中。 Therefore, you can access MouseEvent via the React namespace: React.MouseEvent . 因此,您可以访问MouseEvent通过React命名空间: React.MouseEvent As you have already imported everything into a single variable, you can't import something specific in addition. 由于您已经将所有内容都导入到单个变量中,因此您不能再导入特定内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM