简体   繁体   中英

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

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 <script type='text/babel'> and using babel's browser.js to convert this to JS client-side in the browser.

However, I'm now trying to break out my components into individual files, transpile them, and then serve the transpiled JS to the client rather than have that transpilation done client-side.

I'm confused on how to properly import ReactJS into my component JSX files. I haven't built large JS applications before, so I'm not familiar with the ways to import libraries into other modules.

Here's one of my component JSX files:

var SidebarFilter = React.createClass({
  render: function() {
    return (
        <div className="btn-group">
          Some markup removed for brevity. 
        </div>
    );
  }
});

In my main html file, if I have:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>

Prior to any of my <script> tags for my components, everything works fine. But if the components are placed above the react/reactdom script tags, it doesn't work.

I've seen javascript has an import and there is also require , but I'm not sure what the differences are, which is better to use when, and if either/both require any additional building or if they're used right in the browser.

Thanks!

If you are just learning react then your way of doing using script tag is inside html fine.

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>

If you want to develop an application which can be deployed to production you need to follow following steps. No doubt there are much better tutorial available over the internet but it will give you some idea.

1.Need Browserfiy or Webpack:

In browsers you can not require or import modules as you usually do while writing node.js code. With the help of Browserify/Webpack you can write code that uses require/import in the same way that you would use it in node environment. I am assuming you will use webpack considering its popularity.

2. Install dependencies (es6)

These are minimal dependencies you need in your project ( package.json ) to get it working

  "devDependencies": {
        "babel-cli": "^6.3.17",
        "babel-core": "^6.3.21",
        "babel-eslint": "^5.0.0-beta6",
        "babel-loader": "^6.2.0",
        "babel-preset-es2015": "^6.3.13",
        "babel-preset-react": "^6.3.13",
        "babel-preset-stage-3": "^6.3.13",
        "css-loader": "^0.23.0",
        "eslint": "^1.10.3",
        "eslint-loader": "^1.1.1",
        "eslint-plugin-react": "^3.12.0",
        "style-loader": "^0.13.0",
        "webpack": "^1.12.9",
        "webpack-dev-server": "^1.14.0"
      },
      "dependencies": {
        "react": "^15.0.0-rc.1",
    "react-dom": "^15.0.0-rc.1"

3.Write your webpack-config.js file

A sample webpack config file should like this. Don't ask me about each bit of it but rather have a look on webpack tutorial because I can not explain everything here. Just remember the fact that Webpack is a module bundler that bundles javascript and other assets for the browser.

var path    = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'source-map',
  entry: {
    main: [
      'webpack-dev-server/client?http://localhost:8080',
      'webpack/hot/only-dev-server',
      './src/index.js'
    ]
  },
  output: {
    path: path.join(__dirname, 'public'),
    publicPath: 'http://localhost:8080/public/',
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
   loaders: [
      {
        test      : /\.jsx?$/,
        include   : path.join(__dirname, 'src'),
        loader    : 'react-hot!babel'
      },
      {
        test      : /\.scss$/,
        include   : path.join(__dirname, 'sass'),
        loaders   : ["style", "css?sourceMap", "sass?sourceMap"]
      },
      {
          test    : /\.(png|jpg|svg)$/,
          include : path.join(__dirname, 'img'),
          loader  : 'url-loader?limit=30000&name=images/[name].[ext]'
     } // inline base64 URLs for <=30k images, direct URLs for the rest
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};

4.Set up entry point and routes for your application

src->index.js src->routes.js

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {Router,browserHistory} from 'react-router';
import routes from './routes';

ReactDOM.render(
    <Router routes={routes} history={browserHistory}/>
  , document.querySelector('.init')
);

routes.js

import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/app';
import Home from './components/home';


module.exports = (
       <Route path="/" component={App}>
           <IndexRoute component={Home}/>
       </Route>
)

5.Setup index.html in your project root

<!DOCTYPE html>
<html>
  <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Welcome to ReactJs</title>
  </head>
  <body>
    <div class="init"></div>
  </body>
  <script src="./public/bundle.js"></script>
</html>

6.Running

Form your project root type

webpack-dev-server --progress --colors

import and require

import and require are very similar in functionality. Only difference is that import is new syntactic sugar available with es6 while require is used with es5.

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.

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