简体   繁体   English

如何在单独的文件中正确存储React组件并导入React?

[英]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. 我已经完成了一些React教程的介绍,并且我试图将我的一些知识用到目前为止。 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. 我已成功在<script type='text/babel'>创建了一些组件,并使用babel的browser.js将其转换为浏览器中的JS客户端。

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. 但是,我现在正试图将我的组件分解为单个文件,转换它们,然后将已转换的JS提供给客户端,而不是在客户端完成转换。

I'm confused on how to properly import ReactJS into my component JSX files. 我对如何将ReactJS正确导入我的组件JSX文件感到困惑。 I haven't built large JS applications before, so I'm not familiar with the ways to import libraries into other modules. 我之前没有构建过大型JS应用程序,因此我不熟悉将库导入其他模块的方法。

Here's one of my component JSX files: 这是我的组件JSX文件之一:

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: 在我的主html文件中,如果我有:

<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. 在我的组件的任何<script>标签之前,一切正常。 But if the components are placed above the react/reactdom script tags, it doesn't work. 但是,如果组件放在react / reactdom脚本标记之上,则它不起作用。

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. 我已经看到javascript有一个import ,但也有require ,但我不确定有什么不同,哪个更好用,何时,如果其中一个/两个需要任何额外的建筑物或如果它们在正确使用浏览器。

Thanks! 谢谢!

If you are just learning react then your way of doing using script tag is inside html fine. 如果您只是学习反应,那么您使用脚本标记的方式是在html内部。

<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: 1.Need Browserfiy或Webpack:

In browsers you can not require or import modules as you usually do while writing node.js code. 在浏览器中,您不能像编写node.js代码时那样通常requireimport模块。 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. Browserify / Webpack的帮助下,您可以编写使用require/import代码,方法与在节点环境中使用它的方式相同。 I am assuming you will use webpack considering its popularity. 我假设您将使用webpack考虑其受欢迎程度。

2. Install dependencies (es6) 2.安装依赖项(es6)

These are minimal dependencies you need in your project ( package.json ) to get it working 这些是项目( package.json )中所需的最小依赖项,以使其正常工作

  "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 3.写你的webpack-config.js文件

A sample webpack config file should like this. 一个示例webpack配置文件应该是这样的。 Don't ask me about each bit of it but rather have a look on webpack tutorial because I can not explain everything here. 不要问我关于它的每一点,而是看看webpack教程,因为我无法解释这里的一切。 Just remember the fact that Webpack is a module bundler that bundles javascript and other assets for the browser. 请记住, Webpack是一个模块捆绑器,可以为浏览器捆绑javascript和其他资产。

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 4.为您的应用程序设置入口点和路线

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

index.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 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 5.在项目根目录中设置index.html

<!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 6.Running

Form your project root type 形成项目根类型

webpack-dev-server --progress --colors

import and require 进口和要求

import and require are very similar in functionality. importrequire在功能上非常相似。 Only difference is that import is new syntactic sugar available with es6 while require is used with es5. 唯一不同的是import可与ES6而新的语法糖require使用与ES5。

Both import and require are used to modularize javascript applications but they come from different places: importrequire都用于模块化javascript应用程序,但它们来自不同的地方:

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. import语句是ES6的一部分,如果您已经在项目中使用带有babel的ES6,那么您可以正常使用它。 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. 因此,在import React, { PropTypes, Component } from 'react'我们只从react模块导入PropTypes和Component成员,因此我们不必导入整个'react'模块,只导入我们需要的成员,我们将它分配给React变量。

You can read more about import here . 您可以在此处详细了解import

Require 要求

The require statement is part of Node.js module loading system and serves the same purpose as ES6 import . require语句是Node.js模块加载系统的一部分,其作用与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. var React = require('react')将整个react模块导入React变量。

You can read morea bout the Node.js module system here . 您可以在此处阅读更多关于Node.js模块系统的信息

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. 对于这两种情况,我们导入的模块可以来自不同的来源,例如来自npm下载的库(如“react”)或来自您自己的文件,例如您创建和导出的组件。 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. 在第二种情况下,由于它不是来自你的'node_modules'文件夹的npm下载模块,我们必须写入文件的路径。 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 . 要导出模块,您有两个选项, Node.js模块加载系统和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. 正如您所看到的,您的下一步是使用Node.js作为环境来构建React应用程序以及Webpack或Gulp之类的构建工具,以进行转换,缩小等操作。您可以从Webpack教程Cerad在他的评论中指出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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