简体   繁体   中英

Performance of ES6 imports

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM