Performance of ES6 imports

Ben Botvinick

In the React Bootstrap docs, it is suggested that modules be imported individually from single distribution files rather than from the larger distribution file.

import Button from 'react-bootstrap/Button';

// or less ideally
import { Button } from 'react-bootstrap';

Why is the second method less ideal?

CertainPerformance

As that link says:

You should import individual components like: react-bootstrap/Button rather than the entire library. Doing so pulls in only the specific components that you use, which can significantly reduce the amount of code you end up sending to the client.

If you import from react-bootstrap, the client will have to download everything in react-bootstrap. That could end up being quite a large chunk of code. In contrast, if you import from the react-bootstrap/Button, all that needs to be downloaded is the button - nothing extraneous is included.

Compare the file:

https://github.com/react-bootstrap/react-bootstrap/blob/master/src/Button.js

to

https://github.com/react-bootstrap/react-bootstrap/blob/master/src/index.js

As you can see, importing from the Button requires a few imports:

import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';

import { useBootstrapPrefix } from './ThemeProvider';
import SafeAnchor from './SafeAnchor';

But importing from the index.js requires a very large number of imports, 77, to be precise.

export Accordion from './Accordion';
export AccordionToggle, { useAccordionToggle } from './AccordionToggle';
export AccordionCollapse from './AccordionCollapse';
export Alert from './Alert';
export Badge from './Badge';
// and 72 more

If you import from index instead of from Button, you're downloading a lot of code that you don't need, for no good reason.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related