基于React企业级SPA项目搭建全记录

48次阅读

共计 15811 个字符,预计需要花费 40 分钟才能阅读完成。

前言

本文是介绍如何搭建企业级 react 项目,所用的技术都是最新最主流的,后面我会再写一篇《基于 React 企业级 SSR 项目搭建全记录》,敬请期待!

技术选型

Package Name Version
antd ^3.16.6
axios ^0.18.0
connected-react-router ^6.4.0
classnames ^2.2.6
immutable ^4.0.0-rc.12
@loadable/component ^5.10.0
react ^16.8.6
react-redux ^7.0.3
react-router-config ^5.0.0
react-router-dom ^5.0.0
react-scripts 3.0.1
redux ^4.0.1
redux-actions ^2.6.5
redux-logger ^3.0.6
redux-persist ^5.10.0
redux-persist-expire ^1.0.2
redux-persist-transform-immutable ^5.0.0
redux-saga ^1.0.2
history ^4.7.2

使用 create-react-app 创建新项目

create-react-app react-project

目录结构如下所示

    |-- .gitignore
    |-- README.md
    |-- package.json
    |-- yarn.lock
    |-- public
    |   |-- favicon.ico
    |   |-- index.html
    |   |-- logo192.png
    |   |-- logo512.png
    |   |-- manifest.json
    |   |-- robots.txt
    |-- src
        |-- App.css
        |-- App.js
        |-- App.test.js
        |-- index.css
        |-- index.js
        |-- logo.svg
        |-- serviceWorker.js

然后我们把 webpack 暴露出来,执行如下命令:

yarn eject

目录结构如下所示:

    |-- .gitignore
    |-- README.md
    |-- package.json
    |-- yarn.lock
    |-- config
    |   |-- env.js
    |   |-- modules.js
    |   |-- paths.js
    |   |-- pnpTs.js
    |   |-- webpack.config.js
    |   |-- webpackDevServer.config.js
    |   |-- jest
    |       |-- cssTransform.js
    |       |-- fileTransform.js
    |-- public
    |   |-- favicon.ico
    |   |-- index.html
    |   |-- logo192.png
    |   |-- logo512.png
    |   |-- manifest.json
    |   |-- robots.txt
    |-- scripts
    |   |-- build.js
    |   |-- start.js
    |   |-- test.js
    |-- src
        |-- App.css
        |-- App.js
        |-- App.test.js
        |-- index.css
        |-- index.js
        |-- logo.svg
        |-- serviceWorker.js

添加依赖包

"dependencies": {
    "@babel/plugin-proposal-decorators": "^7.4.0",
    "@babel/plugin-syntax-dynamic-import": "^7.2.0",
    "@loadable/component": "^5.10.0",
    "antd": "^3.16.6",
    "axios": "^0.18.0",
    "babel-plugin-import": "^1.11.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.5",
    "classnames": "^2.2.6",
    "connected-react-router": "^6.4.0",
    "history": "^4.7.2",
    "immutable": "^4.0.0-rc.12",
    "node-sass": "^4.11.0",
    "prettier": "^1.16.4",
    "react-redux": "^7.0.3",
    "react-router-config": "^5.0.0",
    "react-router-dom": "^5.0.0",
    "redux": "^4.0.1",
    "redux-actions": "^2.6.5",
    "redux-logger": "^3.0.6",
    "redux-persist": "^5.10.0",
    "redux-persist-expire": "^1.0.2",
    "redux-persist-transform-compress": "^4.2.0",
    "redux-persist-transform-encrypt": "^2.0.1",
    "redux-persist-transform-immutable": "^5.0.0",
    "redux-saga": "^1.0.2"
  },

添加好了依赖包,我们运行起来看看有没有问题yarn start

添加框架基础配置文件

1、添加.editorconfig 文件统一格式化标准

root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.yml]
indent_style = space
indent_size = 2

2、添加.eslintrc 文件代码检验标准

{"extends": ["react-app", "plugin:prettier/recommended"]
}

3、去掉 package.json 里面的 babel 设置,再添加.babelrc 文件对 babel 的支持

{
    "presets": ["react-app"],
    "plugins": [
      [
        "import",
        {
          "libraryName": "antd",
          "libraryDirectory": "es",
          "style": "css"
        },
        "antd"
      ]
    ]
  }
  

目录结构如下所示:

    |-- .babelrc
    |-- .editorconfig
    |-- .gitignore
    |-- README.md
    |-- package.json
    |-- yarn.lock
    |-- config
    |   |-- env.js
    |   |-- modules.js
    |   |-- paths.js
    |   |-- pnpTs.js
    |   |-- webpack.config.js
    |   |-- webpackDevServer.config.js
    |   |-- jest
    |       |-- cssTransform.js
    |       |-- fileTransform.js
    |-- public
    |   |-- favicon.ico
    |   |-- index.html
    |   |-- logo192.png
    |   |-- logo512.png
    |   |-- manifest.json
    |   |-- robots.txt
    |-- scripts
    |   |-- build.js
    |   |-- start.js
    |   |-- test.js
    |-- src
        |-- App.css
        |-- App.js
        |-- App.test.js
        |-- index.css
        |-- index.js
        |-- logo.svg
        |-- serviceWorker.js

代码运行起来看看有没有问题。

删除 src 下所有文件

目录结构如下:

    |-- .babelrc
    |-- .editorconfig
    |-- .gitignore
    |-- README.md
    |-- package.json
    |-- yarn.lock
    |-- config
    |   |-- env.js
    |   |-- modules.js
    |   |-- paths.js
    |   |-- pnpTs.js
    |   |-- webpack.config.js
    |   |-- webpackDevServer.config.js
    |   |-- jest
    |       |-- cssTransform.js
    |       |-- fileTransform.js
    |-- public
    |   |-- favicon.ico
    |   |-- index.html
    |   |-- logo192.png
    |   |-- logo512.png
    |   |-- manifest.json
    |   |-- robots.txt
    |-- scripts
    |   |-- build.js
    |   |-- start.js
    |   |-- test.js
    |-- src

配置 src

1、添加 index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import {ConfigProvider, message} from "antd";
import zhCN from "antd/es/locale/zh_CN";
import moment from "moment";
import "moment/locale/zh-cn";
import * as serviceWorker from "./serviceWorker";
import "./assets/css/index.css";
import "./assets/css/base.scss";
import "./assets/css/override-antd.scss";

moment.locale("zh-cn");
message.config({
  duration: 2,
  maxCount: 1
});
// 去掉所有页面的 console.log
if (process.env.NODE_ENV === "production") {console.log = function() {};}
ReactDOM.render(
  // 增加 antd 对中文的支持
  <ConfigProvider locale={zhCN}>
    <App />
  </ConfigProvider>,
  document.getElementById("root")
);

2、添加 App.js 文件
App.js 里面包含对 redux 的配置,代码如下:

import React, {Component} from "react";
import {Spin} from "antd";
import {Provider} from "react-redux";
import {renderRoutes} from "react-router-config";
import {ConnectedRouter} from "connected-react-router/immutable";
import {PersistGate} from "redux-persist/es/integration/react";
import configureStore, {history} from "./redux/store";
import AppRoute from "./layout/AppRoute";

const {persistor, store} = configureStore();
store.subscribe(() => {// console.log("subscript", store.getState());
});

class App extends Component {constructor(props) {super(props);
  }
  render() {const customContext = React.createContext(null);
    return (<Provider store={store}>
        <PersistGate loading={<Spin />} persistor={persistor}>
          <ConnectedRouter history={history}>
            <AppRoute />
          </ConnectedRouter>
        </PersistGate>
      </Provider>
    );
  }
}

export default App;

3、添加 assets 文件夹
目录结构如下:

|-- assets
            |-- audio
            |-- css
            |-- fonts
            |-- image
            |-- video

4、添加 components 组件文件夹
同时创建 common 文件夹,目录结构如下:

|-- components
            |-- common

5、添加 config 文件夹
并添加 base.config.js 文件,里面包含一些框架基础信息以及后台的 url 和 port 数据,代码如下:

export default {
  company: "Awbeci",
  title: "后台管理系统平台",
  subTitle: "后台管理系统平台",
  copyright: "Copyright © 2019 Awbeci All Rights Reserved.",
  logo: require("../assets/image/hiy_logo.png"),
  host: "http://10.0.91.189",
  port: "19101",
  persist: "root"
};

目录结构如下:

|-- config
            |-- base.conf.js

6、添加 HOC 高阶组件文件夹 (可选)
同时创建 control.js 文件,作用是根据屏幕分辨率自动计算宽高,代码如下:

import React from "react";
import {is, Map, fromJS} from "immutable";

const control = WrappedComponent =>
  class extends React.Component {constructor(props) {super(props);
      this.state = {
        // 可视区高度和宽度
        document: {
          body: {
            width: 0,
            height: 0
          },
          // 侧边栏高度和宽度
          sidebar: {
            width: 0,
            height: 0
          },
          // 内容区域高度和宽度
          content: {
            width: 0,
            height: 0
          },
          header: Map({
            height: 64,
            width: 0,
            menu: Map({
              height: 0,
              width: 0
            })
          })
        }
      };
    }
    componentWillMount() {
      let cw = document.body.clientWidth;
      let ch = document.body.clientHeight;
      this.computedLayout(cw, ch);
    }
    componentDidMount() {window.addEventListener("resize", this.computedLayout);
    }
    componentWillUnmount() {window.removeEventListener("resize", this.computedLayout);
    }
    computedLayout = () => {
      let width = document.body.clientWidth;
      let height = document.body.clientHeight;

      this.setState((state, props) => ({//todo:}));
    };

    shouldComponentUpdate(nextProps, nextState) {const thisProps = this.props || {};
      const thisState = this.state || {};
      nextState = nextState || {};
      nextProps = nextProps || {};

      if (Object.keys(thisProps).length !== Object.keys(nextProps).length || Object.keys(thisState).length !== Object.keys(nextState).length) {return true;}

      for (const key in nextProps) {if (!is(thisProps[key], nextProps[key])) {return true;}
      }

      for (const key in nextState) {if (!is(thisState[key], nextState[key])) {return true;}
      }
      return false;
    }
    render() {return <WrappedComponent {...this.state} {...this.props} />;
    }
  };

export default control;

目录结构如下:

|-- HOC
        |-- control.js

7、添加 app 文件夹
app 文件夹包含框架布局和页面布局组件以及路由等配置文件,目录结构如下:

|-- app
       |-- AppRoute.js
       |-- Loading.js
       |-- RouterView.js
       |-- layout
       |   |-- index.js
       |   |-- index.scss
       |-- master
           |-- index.js
           |-- index.scss

8、添加 pages 文件夹
pages 文件夹包含登录和首页页面文件,目录结构如下:

|-- pages
        |-- Index.js
        |-- NoFound.js
        |-- NoPermission.js
        |-- login
            |-- Login.js
            |-- login.scss

9、添加 redux 文件夹
redux 文件夹包含 redux-actions 和 redux-saga 以及 middleware 中间件配置,目录结构如下:

|-- redux
        |-- reducers.js
        |-- sagas.js
        |-- store.js
        |-- auth
        |   |-- authAction.js
        |   |-- authReducer.js
        |   |-- authSaga.js
        |-- layout
        |   |-- layoutPageAction.js
        |   |-- layoutPageReducer.js
        |-- middleware
            |-- authTokenMiddleware.js

10、添加 router 文件夹
同时添加 index.js 文件,目录结构如下:

|-- router
        |-- index.js

11、添加 service 文件夹
service 文件夹封装了对后台 api 接口的请求,目录结构如下:

|-- service
        |-- apis
        |   |-- 1.0
        |       |-- index.js
        |       |-- urls.js
        |-- request
            |-- ApiRequest.js

详细配置

上面把代码和目录结构都已经给出,下面我们详细讲解下如何配置 redux、redux-saga、react-acitons、immutable 等等

1、配置 action
配置 action 我们选用的是 redux-actions插件,如下所示

import {createActions} from "redux-actions";

export const authTypes = {
  AUTH_REQUEST: "AUTH_REQUEST",
  AUTH_SUCCESS: "AUTH_SUCCESS",
  AUTH_FAILURE: "AUTH_FAILURE",
  SIGN_OUT: "SIGN_OUT",
  CHANGE_PASSWORD: "CHANGE_PASSWORD"
};

export default createActions({[authTypes.AUTH_REQUEST]: ({username, password}) => ({username, password}),
  [authTypes.AUTH_SUCCESS]: data => ({data}),
  [authTypes.AUTH_FAILURE]: () => ({}),
  [authTypes.SIGN_OUT]: () => ({}),
  [authTypes.CHANGE_PASSWORD]: (oldPassword, newPassword) => ({oldPassword, newPassword})
});

2、配置 reducer
跟 actions 类似,使用的也是 redux-actions, 代码如下:

import {handleActions} from "redux-actions";
import {authTypes} from "./authAction";
import {Map, fromJS, merge} from "immutable";

const initState = fromJS({
  user: null,
  token: ""
});

const authReducer = handleActions(
  {[authTypes.AUTH_SUCCESS]: (state, action) => {
      return state.merge({
        user: action.data.user,
        token: action.data.token
      });
    },
    [authTypes.SIGN_OUT]: (state, action) => {
      return state.merge({
        user: null,
        token: ""
      });
    }
  },
  initState
);

export default authReducer;

添加完了,不要忘了注册一下 reducer

import {combineReducers} from "redux";
import {connectRouter, LOCATION_CHANGE} from "connected-react-router/immutable";
import layoutReducer from "./layout/layoutReducer";
import authReducer from "./auth/authReducer";

export default history =>
  combineReducers({router: connectRouter(history),
    layoutReducer,
    authReducer
  });

3、配置 redux-saga

代码如下所示:

import {call, put, takeLatest, select} from "redux-saga/effects";
import {push} from "connected-react-router";
import authAction, {authTypes} from "./authAction";
import {layoutPageTypes} from "../layout/layoutAction";
import {message} from "antd";
import Apis from "../../service/apis/1.0";
import config from "../../config/base.conf";

function strokeItem(name, value) {localStorage.setItem(name, value);
}

function clearItem(name) {localStorage.removeItem(name);
}

function* test() {
  yield put({
    type: authTypes.AUTH_SUCCESS,
    data: {
      user: {name: "Awbeci"},
      token: "awbeci token"
    }
  });
  yield put({
    type: layoutPageTypes.GET_MENUS,
    menus: [
      {
        icon: "file",
        id: 1,
        isShow: "1",
        title: "页面一",
        url: "/"
      },
      {
        icon: "file",
        id: 2,
        isShow: "1",
        title: "页面二",
        url: "/departmentManage"
      },
      {
        icon: "file",
        id: 3,
        isShow: "1",
        title: "页面三",
        url: "/userManage"
      }
    ]
  });
  yield put({
    type: layoutPageTypes.SAVE_MENU_INDEX,
    payload: {keyPath: ["1"]
    }
  });
  yield put(push("/"));
}

function* signout(action) {yield call(clearItem, "token");
  yield call(clearItem, `persist:${config.persist}`);

  // 清除 token
  // 设置选中第一个菜单
  yield put({
    type: layoutPageTypes.SAVE_MENU_INDEX,
    payload: {keyPath: ["126"]
    }
  });
  yield put({
    type: layoutPageTypes.SAVE_MENU_COLLAPSED,
    payload: {collapsed: false}
  });
  yield put({
    type: layoutPageTypes.GET_MENUS,
    menus: []});
  // 跳转到登录页面
  yield put(push("/login"));
}

function* signin(action) {
  try {yield call(test);
  } catch (error) {message.info("用户名或密码错误");
    yield call(clearItem, "token");
  } finally {}}

export default function* watchAuthRoot() {yield takeLatest(authTypes.AUTH_REQUEST, signin);
  yield takeLatest(authTypes.SIGN_OUT, signout);
}

添加 saga 文件不要忘了注册一下,如下:

import {all, fork} from "redux-saga/effects";
import authSaga from "./auth/authSaga";

/* 添加对 action 的监听 */
export default function* rootSaga() {yield all([fork(authSaga)]);
}

4、配置 store
配置 store 的时候其实已经把 redux-logger、redux-persist、immutable.js 一起配置了,代码如下所示:

import {createStore, compose, applyMiddleware} from "redux";
import {routerMiddleware} from "connected-react-router/immutable";

import {createMigrate, persistStore, persistReducer} from "redux-persist";
import createEncryptor from "redux-persist-transform-encrypt";
import immutableTransform from "redux-persist-transform-immutable";
import storage from "redux-persist/es/storage";

import createSagaMiddleware from "redux-saga";
import logger from "redux-logger";
import {createBrowserHistory} from "history";
import createRootReducer from "./reducers";
import rootSaga from "./sagas";
import config from "../config/base.conf";
import {authTokenMiddleware} from "./middleware/authTokenMiddleware";

export const history = createBrowserHistory();
// create the router history middleware
const historyRouterMiddleware = routerMiddleware(history);
// create the saga middleware
const sagaMiddleware = createSagaMiddleware();

// 组合 middleware
const middleWares = [sagaMiddleware, historyRouterMiddleware, logger];

const migrations = {
  0: state => {
    return {
      ...state,
      device: undefined
    };
  },
  2: state => {
    return {device: state.device};
  }
};

const encryptor = createEncryptor({
  secretKey: "hiynn",
  onError: function(error) {}});

const persistConfig = {
  transforms: [immutableTransform()
    // encryptor
  ],
  key: config.persist,
  storage,
  version: 2,
  migrate: createMigrate(migrations, { debug: false})
};

const finalReducer = persistReducer(persistConfig, createRootReducer(history));
export default function configureStore(preloadedState) {const store = createStore(finalReducer, preloadedState, compose(applyMiddleware(...middleWares)));
  let persistor = persistStore(store);
  sagaMiddleware.run(rootSaga);
  return {persistor, store};
}

5、使用 store
在 App.js 文件中添加对 store 的引用,代码如下:

import React, {Component} from "react";
import {Spin} from "antd";
import {Provider} from "react-redux";
import {renderRoutes} from "react-router-config";
import {ConnectedRouter} from "connected-react-router/immutable";
import {PersistGate} from "redux-persist/es/integration/react";
import configureStore, {history} from "./redux/store";
import AppRoute from "./app/AppRoute";

const {persistor, store} = configureStore();
store.subscribe(() => {// console.log("subscript", store.getState());
});

class App extends Component {constructor(props) {super(props);
  }
  render() {const customContext = React.createContext(null);
    return (<Provider store={store}>
        <PersistGate loading={<Spin />} persistor={persistor}>
          <ConnectedRouter history={history}>
            <AppRoute />
          </ConnectedRouter>
        </PersistGate>
      </Provider>
    );
  }
}

export default App;

6、配置 middleware
中间件作用是当刷新页面的时候重新把 token 设置到 ApiRequest 这样 token 就不会丢失了。

import {REHYDRATE} from "redux-persist/lib/constants";
import ApiRequest from "../../service/request/ApiRequest";
import {authTypes} from "../auth/authAction";
import {fromJS} from "immutable";

/** 保存 token 中间件 */
export const authTokenMiddleware = store => next => action => {
  /** 当刷新页面 persist 会触发 action = REHYDRATE*/
  if (action.type === REHYDRATE) {if (typeof action.payload !== "undefined") {
      let authReducer = action.payload.authReducer;
      if (authReducer) {const token = authReducer.get("token");
        ApiRequest.setToken(token ? token : null);
      }
    }
  }
  /** 当登录成功会触发 action = AUTH_SUCCESS*/
  if (action.type === authTypes.AUTH_SUCCESS) {ApiRequest.setToken(action.data.token);
  }
  return next(action);
};

7、封装 axios
包含 get、post、delete、put、upload 等等

import axios from "axios";
import {message} from "antd";
import config from "../../config/base.conf";

/**
 * Http 服务类
 * get
 * post
 * upload
 * put
 * patch
 * delete
 */
class ApiRequest {constructor() {
    // 创建 axios 实例
    this.instance = axios.create({baseURL: `${config.host}:${config.port}`
    });
  }

  /**
   * 通过 authTokenMiddleware 中间件监听 action=REHYDRATE|AUTH_SUCCESS 来设置 token
   */
  setToken = token => {this.instance.defaults.headers.common["Authorization"] = token;
  };

  authentication = str => {let errJson = JSON.parse(str);
    if (errJson.response && errJson.response.status === 401) {message.error("用户认证出错,正在跳转登录页面!");
      setTimeout(() => {localStorage.removeItem(`persist:${config.persist}`);
        window.location.href = "/login";
      }, 1500);
    }
  };

  upload(url, formData) {return new Promise((resolve, reject) => {
      this.instance
        .post(url, formData, {
          headers: {"Content-Type": "multipart/form-data"}
        })
        .then(({data}) => {resolve(data);
        })
        .catch(error => {let errStr = JSON.stringify(error);
          this.authentication(errStr);
          reject(errStr);
        });
    });
  }

  get(url, params = {}) {return new Promise((resolve, reject) => {
      this.instance
        .get(url, { params: { ...params} })
        .then(({data}) => {resolve(data);
        })
        .catch(error => {let errStr = JSON.stringify(error);
          this.authentication(errStr);
          reject(errStr);
        });
    });
  }

  delete(url, params = {}) {return new Promise((resolve, reject) => {
      this.instance
        .delete(url, { params: { ...params} })
        .then(({data}) => {resolve(data);
        })
        .catch(error => {let errStr = JSON.stringify(error);
          this.authentication(errStr);
          reject(errStr);
        });
    });
  }

  post(url, params = {}) {return new Promise((resolve, reject) => {
      this.instance
        .post(url, { ...params})
        .then(({data}) => {resolve(data);
        })
        .catch(error => {let errStr = JSON.stringify(error);
          if (url.includes("login")) {reject(errStr);
          } else {this.authentication(errStr);
          }
        });
    });
  }

  put(url, params = {}) {return new Promise((resolve, reject) => {
      this.instance
        .put(url, { ...params})
        .then(({data}) => {resolve(data);
        })
        .catch(error => {let errStr = JSON.stringify(error);
          this.authentication(errStr);
          reject(errStr);
        });
    });
  }

  patch(url, params = {}) {return new Promise((resolve, reject) => {
      this.instance
        .patch(url, { ...params})
        .then(({data}) => {resolve(data);
        })
        .catch(error => {let errStr = JSON.stringify(error);
          this.authentication(errStr);
          reject(errStr);
        });
    });
  }
}

export default new ApiRequest();

总结

1、其实 redux、redux-saga、react-router 都有介绍如何配置,只是整合时插件前后顺序有问题
2、ConnectedRouter 是连接 redux reducer 和 react-router 的插件,并且要支持 immutable.js
3、antd-layoutui
4、本文代码

正文完
 0