注:前端技术更新太快,本文是基于React-Router 1.0写的。
工具集
一直以来PHPStorm堪称PHP开发神器,本想用一个工具搞定,无奈还没有支持ES6,太多的错误提示不忍直视。于是换成VSC,够用就行。
包管理需要用到npm,天朝网络的原因,最好装cnpm,方便有效。
创建项目
用npm初始化项目,然后编辑package.json如下:
{ "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 install
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都是必须的。
代码结构
入口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文件,所以只要引入这个打包生成的文件即可。
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;