前言
本文是介绍如何搭建企业级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];
// 加密localstorage
const encryptor = createEncryptor({
secretKey: "hiynn",
onError: function(error) {}
});
const persistConfig = {
transforms: [
immutableTransform()
],
key: config.persist,
storage,
version: 2
};
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;
AppRoute.js
import React, { Component } from "react";
import { connect } from "react-redux";
import { Switch, Redirect } from "react-router";
import { BrowserRouter as Router, HashRouter, Route } from "react-router-dom";
import Login from "../pages/login/Login";
import LayoutContainer from "./layout";
import NoFound from "../pages/NoFound";
@connect(store => ({
store
}))
class AppRoute extends Component {
// 用户认证
Authentication() {
return this.props.store.authReducer.get("token") ? <Redirect to="/" /> : <Login />;
}
render() {
return (
<>
{/* 解决github gh-pages发布必须以Hash浏览否则history模式就会报错问题,
如果想使用history模式去掉下面的HashRouter即可 */}
{/* <HashRouter> */}
<Switch>
<Route path="/login" render={() => this.Authentication()} />
<Route path="/" exact component={LayoutContainer} />
<Route component={NoFound} />
</Switch>
{/* </HashRouter> */}
</>
);
}
}
export default AppRoute;
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、配置静态路由
import React from "react";
import loadable from "@loadable/component";
import RouterView from "../app/RouterView";
import NoFound from "../pages/NoFound";
import NoPermission from "../pages/NoPermission";
import Loading from "../app/Loading";
const Index = loadable(() => import("../pages/Index"), { fallback: <Loading /> });
// 注意区分前端路由和前端菜单是两个不同的东西
// 注:菜单和路由都是基于该路由数据生成
// 菜单可以不全部展示在页面上(隐藏),但路由必须全部要定义
// 后期可以加入权限控制
const routes = [
{
key: "1",
name: "首页",
path: "/",
exact: true,
component: Index
}
];
export default routes;
静态路由需要react-router-config配合使用,代码如下:
import { renderRoutes } from "react-router-config";
import routes from "../../router";
// 这里的routes就是上面的路由文件
renderRoutes(routes)
8、封装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、React项目集成Immutable.js
4、antd-layoutui
5、本文代码
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。