4
votes

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
@ShubhamKhatri I already use uglify js. But there is an increase in size when we use import {Button} from 'react-bootstrap' as whole react-bootstrap gets imported but in {Button} the Button component gets imported. Its tried and tested that there is increase in size - iamsaksham
Hm, I think, because of the way react-bootstrap is bundled, it is not possible for UglifyJS to only import everything necessary. require calls kill all possible optimization. If you want to keep your app size small the way @iamsaksham is doing it, is the correct way. - Sebastian Sebald
@SebastianSebald I haven't tested it but I think {Button} should import only the button component and not everything that what {} are for. If you compare a similar approach is done with destructuring props - Shubham Khatri
@ShubhamKhatri lets not deviate from the issue, importing react-bootstrap for sure increases size but react-bootstrap/lib/Button is quite cheap in size. - iamsaksham
Yes it only imports the Button, but it will include the whole library in the bundle anyway :( This does not happen if you import from lib. - Sebastian Sebald

1 Answers

1
votes

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"
}