Difference between import * as Button and import {Button}

社会主义新天地 提交于 2019-12-25 09:03:20

问题


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 the react 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 containing createElement, 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

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