且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-16 14:33:01

如果你刚学习反应那么你的使用脚本标签的方式是在html内部。

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或Webpack:

在浏览器中,您不能需要导入模块通常在编写node.js代码时执行。在 Browserify / Webpack 的帮助下,您可以编写使用 require / import 的代码,方法与在节点环境中使用它的方式相同。我假设您将使用 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。安装依赖项(es6)

这些是项目中需要的最小依赖项( package.json )让它运作

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

示例 webpack 配置文件应该是这样的。不要问我关于它的每一点,而是看看 webpack 教程,因为我无法解释这里的一切。请记住,
Webpack 是一个模块捆绑包,它捆绑了 javascript 和浏览器的其他资产。

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

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

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

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

<!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.运行

形成项目根类型

webpack-dev-server --progress --colors

导入和需要

import require 在功能上非常相似。唯一的区别是 import 是es6可用的新语法糖,而 require 与es5一起使用。

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.