Import React vs React, { Component }

孤街浪徒 提交于 2019-12-17 18:56:05

问题


Import React vs Import React, { Component }

Which one is better and why?

Or does it make no difference other than writing less code later on?

Does writing { Component } mean it only imports the Component object?


回答1:


import React, { Component } lets you do class Menu extends Component instead of class Menu extends React.Component. It's less typing and duplication of the React namespace, which is generally a desired modern coding convention.

Additionally, tools like Webpack 2 and Rollup do "tree shaking," meaning any unused exports are not bundled into your final code. With import React/React.Component you are guaranteeing all of React's source code will be bundled. With import { Component }, some tools will only bundle the code needed to use the Component class, excluding the rest of React.

The above paragraph is irrelevant in this specific case, because you always need to have React in the current namespace to write JSX, but only importing the exact modules you need in other cases may lead to smaller bundled code in the end.

Beyond that it's entirely personal preference.




回答2:


What these are are named imports or namespace imports. What they do is basically copy over the module's contents into the namespace allowing:

import React, { Component } from 'react';

class SomeComponent extends Component { ... }

Normally, we'd extend React.Component, but since the Component module is imported into the namespace, we can just reference it with Component, React. is not needed. All React modules are imported, but the modules inside the curly brackets are imported in such a way that the React namespace prefix is not needed when accessing.




回答3:


TLDR;

it's entirely personal preference.

Just a note…

import React, { Component } lets you do class Menu extends Component instead of class Menu extends React.Component. It's less typing…

If you want to do less typing, then don't import Component in addition to React.

import React, { Component } from 'react';
class Menu from Component {

is more typing than:

import React form 'react';
class Menu from React.Component {

even if you consider auto-completion. ;)



来源:https://stackoverflow.com/questions/39361282/import-react-vs-react-component

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