How to properly store React components in separate files and import React?

前端 未结 2 506
无人共我
无人共我 2021-02-04 21:33

I\'ve completed a few intro to React tutorials and am trying to put some of my knowledge so far to use. I\'ve successfully created some components inside of a

2条回答
  •  礼貌的吻别
    2021-02-04 21:42

    Both import and require are used to modularize javascript applications but they come from different places:

    Import

    The import statement is part of ES6 and if you're already using ES6 with babel in your project you can use it just fine. It imports a previously exported module (or some parts of it) into the file in which it's declared.

    So, in import React, { PropTypes, Component } from 'react' we are importing only the PropTypes and Component members from the react module, so we don't have to import the whole 'react' module and only the members we need, and we assign it to the React variable.

    You can read more about import here.

    Require

    The require statement is part of Node.js module loading system and serves the same purpose as ES6 import. It allows you to import previously exported modules or parts of it.

    var React = require('react') is importing the whole react module into the React variable.

    You can read morea bout the Node.js module system here.

    For both cases the modules we are importing can come from different sources, like from npm downloaded libraries (like 'react') or from your own files, for example the components you have created and exported. In the second case, since its not an npm downloaded module, which comes from your 'node_modules' folder, we have to write the path to the file. For example:

    import MyComponent from './components/MyComponent.js';

    or

    var MyComponent = require(./components/MyComponent.js;

    You can use whichever you prefer.

    Exporting modules

    To export modules you have the same two options, Node.js module loading system and ES6.

    As you can see, your next step would be to use Node.js as an environment to build React apps as well as one of the build tools such as Webpack or Gulp, to do the transpiling, minifying, etc. You can start with the Webpack tutorial Cerad pointed to in his comment.

提交回复
热议问题