我推薦用腳手架做爲開始,剛開始學習時一開始就搗騰 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>
替換完成!