Typescript: How to import specific component from react-bootstrap

烈酒焚心 提交于 2019-12-10 10:37:39

问题


Earlier my app was in ReactJs + React-bootstrap. Now I'm using Typescript + ReactJs + React-bootstrap

To reduce the size of the app for production Earlier I used to import react-bootstrap components using - import Button from 'react-bootstrap/lib/Button'

After adding Typescript it shows the following error

ERROR in [at-loader] ./components/Hello.tsx:6:8 TS1192: Module ''react-bootstrap/lib/Button'' has no default export.

Trial 1

import {Button} from 'react-bootstrap/lib/Button' but in this case Button is undefined.

Trial 2

import * as Button from 'react-bootstrap/lib/Button' but in this case another error pops out

ERROR in [at-loader] ./components/Hello.tsx:54:12 TS2604: JSX element type 'Button' does not have any construct or call signatures.

This error shows error in line <Button onClick={handleClick} bsStyle="danger" bsClass="glyphicon glyphicon-new-window"></Button>

Though import {Button} from 'react-bootstrap' works fine but this is not desired because it results in increasing the size of the app by 200kbs for me.

How can we import specific component from react-bootstrap using Typescript??


回答1:


Since TypeScript adheres to the ESModule spec but the lib is using CommonJS, you have to to the sam, you did with the React import when you switched to TypeScript.

JS

import React from 'react'
import Button from 'react-bootstrap/lib/Button'

TypeScript

import * as React from 'react'
import * as Button from 'react-bootstrap/lib/Button'

Shameless self plug: I wrote about the reason for this here. I guess you will run into this issue in the future again :)

This is the version i used:

{
  "@types/react-bootstrap": "^0.0.47",
  "react-bootstrap": "^0.30.8"
}


来源:https://stackoverflow.com/questions/43338173/typescript-how-to-import-specific-component-from-react-bootstrap

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