问题
I am new to Typescript
and I'm trying to import a react-bootstrap Button
using
case 1: import {Button} from 'react-bootstrap/lib/Button'
case 2: import * as Button from 'react-bootstrap/lib/Button'
Both the ways dont throw any error on import statement but throws error when this Button is rendered using <Button bsClass="glyphicon glyphicon-new-window"></Button>
In case 1 there is no compile time error but Button is undefined
In case 2 Typescript throws the following compile time error TS2604: JSX element type 'Button' does not have any construct or call signatures.
Although this works in JS import Button from 'react-bootstrap/lib/Button'
. Now I'm not able to figure out why any of the method aint working and what is the difference between the two methods?
回答1:
Let's say the below are the exports of a button.ts
file:
export function Button () {}
export function Toggle () {}
Case 1
Using import { Button } from 'button'
will give you the Button
function.
Cas 2
Using import * as Button from 'button'
will give you an Object
locally named Button
with two members: Button
and Toggle
. Basically
const Button = { Button:Button, Toggle:Toggle }
You can find more information about the module syntax here.
Since you explicitly asked about TypeScript, I guess you also might run into the issue why you no longer can do import React from ' react'
and instead have to use the * as <x>
syntax:
This is due to the fact that TypeScript adheres the ESModule specification. Babel (previously) did some magic under the hood for us developers that basically was an interop between ESModules and CommonJS modules.
Imports like
import React from 'react'
will try to pick up the default member in thereact
module. If the module is bundled with CJS this member (usually) doesn’t exist. Thus, you have to use* as React from 'react'
in order to obtain the exported object containingcreateElement
,PropTypes
and so on.Source
回答2:
It depends on what kind of object is exported from the certain module. In a simple words. Lets say module "a" exported some object:
export {
Button: function() { some button construction code},
Link: {}
}
In case of
import {Button} from 'a'
Button
will be function() { some button construction code}
In case of
import * as Button from 'a'
Button
will be whole exported object:
{
Button: function() {},
Link: {}
}
For more details you can check the documentation.
来源:https://stackoverflow.com/questions/43385452/difference-between-import-as-button-and-import-button