使用React、React-Router、Webpack開發SPA

注:前端技術更新太快,本文是基於React-Router 1.0寫的。css

工具集

一直以來PHPStorm堪稱PHP開發神器,本想用一個工具搞定,無奈尚未支持ES6,太多的錯誤提示不忍直視。因而換成VSC,夠用就行。html

包管理須要用到npm, 天朝網絡的緣由,最好裝cnpm,方便有效。前端

建立項目

用npm初始化項目,而後編輯package.json以下:node

{
  "name": "react app",
  "version": "1.0.0",
  "description": "react demo app",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --hot --progress --colors",
    "build": "webpack --progress --colors"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-loader": "^6.0.1",
    "babel-preset-es2015": "^6.1.2",
    "babel-preset-react": "^6.1.2",
    "jsx-loader": "^0.13.2",
    "react-router": "^1.0.0",
    "react-hot-loader": "^1.3.0",
    "webpack": "^1.12.3",
    "webpack-dev-server": "^1.12.1"
  },
  "dependencies": {
    "react": "^0.14.2",
    "react-dom": "^0.14.2"
  }
}

用npm install 或者 cnpm installreact

Webpack打包配置

var webpack = require('webpack');  
module.exports = {  
    entry: [
      'webpack/hot/only-dev-server',
      "./js/app.jsx"
    ],
    output: {
        path: __dirname + '/build',
        filename: "bundle.js"
    },
    module: {
        loaders: [
            { test: /\.jsx$/, exclude: /node_modules/, loader: 'babel-loader',query: {presets: ['es2015', 'react']}},
            { test: /\.js?$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/},
            { test: /\.css$/, loader: "style!css" }
        ]
    },
    plugins: [
      new webpack.NoErrorsPlugin()
    ]

};

須要注意的是,因爲計劃使用ES6語法和JSX寫業務程序,因此es2015和jsx的loader都是必須的。webpack

代碼結構

app files

入口index.html

<!doctype html>  
<html lang="en">  
  <head>
    <meta charset="utf-8">
    <title>New React App</title>
  </head>
  <body>
    <section id="react"></section>
    <script src="bundle.js"></script>
  </body>
</html>

因爲webpack打包後會生成bundle.js文件,因此只要引入這個打包生成的文件便可。web

App

import React from 'react';  
import {render} from 'react-dom';
import { Router, Route, Link } from 'react-router'

import LoginHandler from './components/Login.jsx';

const App = React.createClass({  
  render() {
    return (
    <div className="nav">
        <Link to="/">Home</Link>
        <Link to="login">Login</Link>
        {this.props.children}
    </div>
    );
  }
});


const routes = (
  <Router>
    <Route  path="/" component={App}>
      <Route path="/login" component={LoginHandler}/>
    </Route>
  </Router>
);

render(routes, document.body);

Login 組件

import React from 'react';

const Login = React.createClass({ 

  render:function() {
    return(<div>Welcome!</div>);
  }
});

export default Login;

運行測試

命令行輸入 npm start,啓動webpack自帶服務器,查看效果。npm

相關文章
相關標籤/搜索