前言
最近項目用到react,其實前年我就開始接觸react,時光匆匆,一直沒有時間整理下來(太懶啦)!如今再次用到,稱工作間隙,對全家桶做一次總結,項目源碼地址。廢話不多說,上碼。
創建一個文件目錄並初始化package.json
mkdir react-Buckets
npm init
填好相關信息如圖
安裝webpack
- 需要有全局安裝哦,不然一會用webpack編譯時會報錯的
- 關於裝依賴加入package.json時,加 --save-dev表示開發環境要用的依賴,如果加 -save表示生產環境依然要用的依賴。
npm install --save-dev webpack
- 手動添加webpack配置文件
touch webpack.dev.config.js
- 配置文件
var path=require('path');
module.exports={
// 入口文件指向src/index.js
entry:path.join(__dirname,'src/index.js'),
//打包后的文件到當前目錄下的dist文件夾,名為bundle.js
output:{
path:path.join(__dirname,'./dist'),
filename:'bundle.js'
}
};
- 生成主要文件目錄
mkdir src && cd src
touch index.js
- 入口文件寫點內容
document.getElementById('app').innerHTML='This is my React!';
- 進行一個小測試
webpack --config webpack.dev.config.js
效果如圖
- 此時發現目錄下生成了 dist/bundle.js
- 我們在dist目錄下新建 index.html
touch ./dist/index.html
- 編輯index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="./bundle.js"></script>
</body>
</html>
- 在瀏覽器打開index.html
- 編譯優化:我們每次編譯都要輸那么長串的命令太難記,我們在package.json中設置命令,簡化它:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build":"webpack --config webpack.dev.config.js"
},
- 運行的時候使用,此處要注意下webpack的版本,如果是4.0則會提示裝webpack-cli模塊
npm run build
安裝與配置babel
平時大家在項目中不管用的vue還是react,應該大多都開始用ES6或ES7的語法了吧。想必都了解如果想讓瀏覽器可以直接識別,基本都會選用babel插件進行編譯轉換。下面為大家一一介紹:
- babel-core 調用Babel的API進行轉碼使用
- babel-loader 允許使用babel和webpack將文件轉化成JavaScript
- babel-preset-es2015 將ES6解析成ES5
- babel-preset-react 解析JSX語法
- babel-preset-stage-0 解析ES7提案
那么先統一安裝下
npm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-0
安裝好后,添加配置文件
touch .babelrc
打開文件,對babel進行配置,注:此處stage-0是包含stage-1,stage-2,stage-3
{
"presets":[
"es2015",
"react",
"stage-0"
],
"plugins":[]
}
- 在webpack配置中加入babel,修改webpack.dev.config.js
在配置babel-loader模塊時,將cacheDirectory=true是為了緩存編譯結果,優化下次編譯的。
modle:{
rules:[{
test:/\.js$/,
use:['babel-loader?cacheDirectory=true'],
include:path.join(__dirname,'src')
}]
}
- 配置好了后,對babel進行測試,修改src/index.js
//使用ES6的箭頭函數
var babeltest=()=>
console.log('This is Babel Test!');
babeltest();
安裝與配置react
- 安裝
npm install --save react react-dom
- 頁面中引入src/index.js
import React from 'react';
import ReactDom from 'react-dom';
ReactDom.render(
<div>First React!</div>,
document.getElementById('app')
)
- 自定義一個組件,建好目錄,我們把組件放入src/components中
cd src
mkdir components && cd components
mkdir Hello && cd Hello
touch Hello.js
- 進入Hello.js
import React, {Component} from 'react';
export default class Hello extends Component{
render(){
return(
<div>Hello React!</div>
)
}
}
- 引用Hello.js,進入src/index.js
import React from 'react';
import ReactDom from 'react-dom';
import Hello from './components/Hello/Hello';
ReactDom.render(
<Hello/>,
document.getElementById('app');
)
路由配置react-router
- 安裝與目錄新建
npm install --save react-router-dom
cd src
mkdir router && touch router/router.js
- 打開router.js,配置home和about頁面
import React from 'react';
import {BrowserRoter as Router,Route,Swith,Link} from 'react-router-dom';
import Home from '../pages/Home/Home';
import Page1 from '../pages/About/About';
const getRouter=()=>(
<Router>
<div>
<ul>
<li><Link to="/">首頁</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<Switch>
<Route exact path="/" componen={Home} />
<Route path="/about" component={About}/>
</Switch>
</div>
</Router>
);
export default getRouter;
- 新建好組件文件目錄
cd src
mkdir pages && cd pages
mkdir Home && touch Home/Home.js
mkdet About && touch About/About.js
- 打開Home.js,定義內容
import React,{Component} from 'react';
export default class Home extends Component{
render(){
return(
<div>
<h1>歡迎來到我的網站</h1>
<p>這是一個首頁</p>
</div>
)
}
}
- 打開About.js,定義內容
import React,{Component} from 'react';
export default class About extends Component{
render(){
return(
<div>
<h2>關於我們</h2>
<p>自定義react全家桶</p>
</div>
)
}
}
- 在入口文件src/index.js,引入Router
import React from 'react';
import ReactDom from 'react-dom';
import getRouter from './router/router';
ReactDom.render(
getRouter(),
document.getElementById('app')
)
- 編譯下,效果如圖
npm run build
我們發現頁面是出來了,但是點擊切換不了路由,原因是因為我們需要配置一個web服務器來指向index.html,在這里我們來配置一個webpack-dev-server。
web服務器配置 webpack-dev-server
webpack-dev-server是我們做前后端分離時,常會用到的依賴,它是一個小型的靜態文件服務器,可以為webpack打包后生成的文件提供web服務器功能。
- 安裝,這個和webpack一樣,要有全局安裝才行。
npm install webpack-dev-server@2 --save-dev
- 修改配置文件webpack.dev.config.js
devServer:{
//將服務器根目錄指向打包后的dist文件,默認是指向項目的根目錄
contentBase:path.join(__dirname,'./dist');
}
- 測試
webpack-dev-server --config webpack.dev.config.js
打開http://localhost:8080
8080是默認端口,可更改配置。同樣,我們把編譯命令優化下:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.dev.config.js",
"start": "webpack-dev-server --config webpack.dev.config.js --color --progress"
},
- 小貼示:可以試試打開瀏覽器后,去刪除dist/bundle.js哦,是不是頁面依然可以打開呢,因為webpack-dev-server編譯后會緩存在內存中!
附webpack-dev-server 基本配置
- color : 打印日志為彩色
- progress : 日志顯示進度
- historyApiFallback : 值為Boolean,設為true時,作意404的請求路徑,會指向index.html
- host : 默認為loaclhost,可以設為IP地址,局域網內用其它設備IP訪問
- port : 端口號,默認為8080
- proxy : 代理,比如后端交互的服務器地址為localhost:9000,設置如下
proxy:{
"/api":"htpp://localhost:9000"
}