「 react+react-router4+redux+webpack3+antd 」 專案實踐

zhouyinian發表於2017-12-12

前言

隨著前端的發展,現在好多公司都會在招人簡歷上寫著要熟悉 react vue angular 中的一種,好多朋友之前都是擼 jquery,但是面向工資程式設計,不會這些也不行啊?ok , 轉向 react 好多朋友會直接拿著腳手架跑一個 todolist ,但是好多腳手架 和自己的需求不一樣,並且依賴的外掛框架不斷更新,更新專案依賴又極可能導致專案崩潰,所以,還是建議直接自己從頭搭建一個,用到什麼新的功能隨時往上面新增。我根據一年半react的使用經驗,寫了個簡易的demo, 專案 github 地址 移步這裡,不正確之處還望指出。

專案基本介紹

一 初始化專案,搭建目錄結構

隨便找個資料夾,建立個目錄

mkdir react-first 
cd react-first
npm init
複製程式碼

然後開始傻瓜式的回車,這時候會生成package.json 檔案。

在專案根目錄下建立 src 資料夾,我們的主體程式碼都會寫在這個裡面,在src 下面建立main.js 這個是我們的專案打包入口檔案,和index.html。 同時,在根目錄下建立webpack.config.js 用於配置webpack 打包。

二 安裝專案依賴,配置打包說明

安裝專案依賴(全部依賴移步 package.json 檢視)

npm install react react-dom  react-router-dom --save
複製程式碼

注意: react-router 升級到4 之後,需要安裝的是 react-router-dom

安裝 redux 相關包

npm install redux react-redux redux-thunk --save
複製程式碼

安裝相關語法的解析包

npm install webpack babel-cord babel-loader babel-preset-env  babel-preset-react  --save 
複製程式碼

配置 webpack 打包(完整程式碼移步 專案 檢視)

//定義打包入口
webpack_conf.entry = {
    app: './src/main.js',
};

//指定輸出路徑
webpack_conf.output = {
    path: path.join(__dirname, 'dist'),
    publicPath: '/',
    filename: debug? '[name].js':'[hash:8].[name].js',
    chunkFilename: debug? '[name].js':'[name].[chunkhash].js',
};


// 需要引用的外掛
webpack_conf.plugins = [
    new webpack.DefinePlugin({
        "process.env":{
            NODE_ENV:JSON.stringify(env)
        }
    }),
    new webpack.optimize.CommonsChunkPlugin({
        names: ['vander', 'manifest'],
        minChunks: Infinity
    }),
    new HtmlWebpackPlugin({
        template: path.join(__dirname + `/src/index.html`),
        hash: false,
        favicon: path.join(__dirname,'/src/static/favicon.ico'),
        filename: 'index.html',
        minify: {
            collapseWhitespace: true
        }
    }),
];
if(debug){
    webpack_conf.plugins.push(
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
    )
}else{
    webpack_conf.plugins.push(
        new webpack.optimize.UglifyJsPlugin()
    )
}

// 解析
webpack_conf.module.rules = [
    {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        include: [
            path.resolve(__dirname, "src")
        ],
        loader: "babel-loader",
    },
];
module.exports = webpack_conf;
複製程式碼

在根目錄建立.babelrc 配置babel規則

{
  "presets": ["env","react","stage-0"],
  "comments": false,// 忽略註釋
  "plugins": [
    "syntax-dynamic-import",// 解析import 語法 ,用於懶載入
    "transform-object-rest-spread",// 物件展開符 
    "transform-decorators-legacy",//裝飾模式外掛
    [
      "import", {"libraryName": "antd", "style": true} // 按需載入 antd
    ]
  ]
}
複製程式碼

三. 編寫入口檔案,引入路由

首先貼出一張專案目錄結構圖

「 react+react-router4+redux+webpack3+antd 」 專案實踐

是不是覺得有點跳,剛開始還是 一個index.html 一個main.js , 怎麼突然搞出來這麼多,(別打臉 主要是篇幅有限。大體介紹下每個目錄,

dist:打包生成檔案

componend: 專案的元件,比如 Header,Footer,Dialog等

pages : 包含每個頁面

reduces/stores :redux 相關邏輯

tools: 工具庫。static: 靜態檔案

下面貼下主要的檔案

1 入口檔案 main.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Router } from 'react-router-dom';// 引入router ,同步history 和 store
import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory();
import createStore from './stores/createStore.js';
const initialState = window.___INITIAL_STATE__ || {};
const store = createStore(initialState);

import routers from './pages/index'
const ROOT_NODE = document.getElementById('root');

import './assets/base.less';

const render = (routes) => {
    ReactDOM.render((
        <Provider store={store}>
            <Router onUpdate={() => window.scrollTo(0, 0)} history={history} children={routers}/>
        </Provider>
    ), ROOT_NODE);
};

render(routers);

複製程式碼

2. pages 下面的路由檔案

import React from 'react'
import { Route,Switch, Redirect,
} from 'react-router-dom';
const NotFound = () => (
    <div>not fount</div>
)
import Home from './Home/index';
import About from './About/index'
import Header from '../components/Header/index'
let routes = (
    <div>
        <Header/>
        <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/about" component={About} />
            <Redirect to="/" />
        </Switch>
    </div>
)
export default routes;
複製程式碼

3. 單個模組(以pages/Home 模組為例)

「 react+react-router4+redux+webpack3+antd 」 專案實踐

  1. assets 樣式 檔案
  2. components 主要邏輯 react程式碼
  3. container 高階元件用connect接收redux中狀態
  4. modules redux 中 action 和 reduces 邏輯

更多細節還是希望您多打多試試,本篇幅不是新手教程,react redux 等 語法及 使用等問題還請多看官網文件。最後,如有問題歡迎留言指出,共同學習。

相關文章