我推荐用脚手架做为开始,刚开始学习时一开始就捣腾 Webpack Babel 本身配置运行环境,而后你会发现一堆知识要补充,再而后就忘记了我一开始只是为了跑个 React。css
本文讨论的都是基于 npm 构建的环境,若是直接在浏览器中运行,须要用 es5 直接写,否者会遇到兼容问题。html
下面开始咱们的正题!前端
cnpm install -g create-react-app
关于 npm 加速
问题,请查看上篇react
cd ~/Documents/labs create-react-app reactjs-example
我专门建了个 labs
目录,用来测试各类程序,这样不会把你的磁盘目录弄得很凌乱git
录像es6
cd reactjs-example npm start
录像github
浏览器打开 http://localhost:3000/
npm
看到这个干净的页面,你们能够放心了,环境一切正常json
. ├── README.md | 帮助说明 ├── build | 发布目录 ├── package.json | npm包管理 ├── public | 首页模板 │ ├── favicon.ico │ ├── index.html │ └── manifest.json ├── src | 源码 │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── index.css │ ├── index.js │ ├── logo.svg │ └── registerServiceWorker.js
咱们大部份内容都是在 src 下完成redux
编辑 app.js
文件
import React, {Component} from 'react' const Element1 = () => <h2>组件1 - 常量</h2> export default Element1
输出: 组件1 - 常量
就3行,你们能够本身动手试下
const Element1 = () => <h2>组件1 - 常量</h2>
let Element2 = () => <h2>组件2 - 变量</h2>
function Element3() { return <h2>组件3 - es5 函数</h2> }
let Element4 = () => { return <h2>组件4 - es6 箭头函数</h2> }
class Element5 extends Component { render() { return <h2>组件5 - React.Component 类对象</h2> } }
class Element6 { render() { return <h2>组件6 - es6 class 类对象</h2> } }
运行后报错!
codepen.io 是一个不错的在线调试代码平台,个人 codepen.io/ducafecat/
本文代码 codepen
https://codepen.io/ducafecat/...
cd reactjs-example npm run build
执行成功后会生成 /build
目录,直接放到你的服务器上就能展现了~
录像
build/index.html
,你会发现找不到资源文件,由于默认是指向 /
修改本地容许先打开模板看下
<!DOCTYPE html> <html lang="en"> <head> ... <link rel="manifest" href="%PUBLIC_URL%/manifest.json"> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
这个 %PUBLIC_URL%
是全局变量
咱们编译命令要这样写
- Windows set PUBLIC_URL=./ && npm run build - macOS PUBLIC_URL=./ npm run build
再次打开 build/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> ... <link rel="manifest" href="./manifest.json"> <link rel="shortcut icon" href="./favicon.ico"> <title>React App</title> <link href="./static/css/main.65027555.css" rel="stylesheet"> </head>
替换完成!