简体   繁体   中英

ES6 best way to import React's named imports

I was wondering which of the two way of importing React named imports ( PropTypes , Component ) in ES6 is the best.

First

import React, {PropTypes, Component} from 'react';

which would save a lot of typing specially on components that have lots of props to validate.

Second

import React form 'react';

and then calling them like React.Component when I want to use them.

Is there any performance difference between the two approaches or should I just pick whichever style I am more comfortable with ?

Whatever you prefer, but most importantly - stay consistent .


The community around React and the official docs prefer the second alternative, that's also my personal preference, because it is more descriptive.

import React from 'react';

and use it like

class Welcome extends React.Component { ... }

I would say there is near-zero performance differences.

For me, the main advantages to the later is maintaining namespace: This is a contrived example, because you obviously wouldn't include lodash and underscore -

import { map } form 'lodash';
import { map } from 'underscore'; // oh no map-clash

vs

import lodash from 'lodash';
import underscore from 'underscore'; // lodash.map v underscore.map

However, I generally lean towards the destructured version (the {} version), because it "feels" tidier than these possibly big objects everywhere.

EDIT

One other thing worth noting, are more and more libraries are getting better at writing modules that can be imported as smaller parts of a larger whole - which works particularly well for ES6's import functionality.

For example, if you are only using map from lodash, importing like this:

import map from 'lodash/map';

instead of this:

import { map } from 'lodash';

will result in a much smaller final compiled file (if you have your browseifry/rollup/webpack/[insert flavour of the month] set up correctly) as it will only bring in the required code needed to execute map. Whereas the first one brings in all the things.

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