搭建一个react框架项目
搭建一个react全家桶项目
"antd": "^4.20.5"
"axios": "^0.27.2"
"react": "^18.1.0"
"react-redux": "^8.0.1"
"react-router-dom": "^6.3.0"
"webpack": "^5.64.4"
安装react cli
1 | npm install -g create-react-app |
创建项目
1 | # app 为该项目名称 |
启动项目
1 | cd app |
这样就能够访问react初始界面了。hello world react!
项目引入Ant Design
1 | npm install antd --save |
配置Ant Design按需加载
使用 babel-plugin-import
方式进行按需加载
暴露配置文件:
当我们使用react的脚手架创建了一个react项目后,一定会有一个疑问,那就是为什么create-react-app创建的项目没有webpack.config.js文件!这时就可以用如下命令把配置文件暴露出来。
1 | npm run eject |
在 package.json
中配置 babel
(需要安装 babel-plugin-import
)
1 | npm install babel-plugin-import --save-dev |
babel 配置如下
1 | "babel": { |
使用 babel-plugin-import
的 style 配置来引入样式,需要将配置值从 'style': 'css'
改为 'style': true
,这样会引入 less 文件。
配置Ant Design中文语言,antD默认English
在src/index.js
入口文件配置
1 | import { ConfigProvider } from 'antd'; |
另外需要使用 ConfigProvider
组件把 根组件 包裹起来
1 | <ConfigProvider locale={zh_CN}> |
1 | npm install less less-loader --save-dev |
如果没有暴露配置文件的话需查看package.json
文件中 “scripts”
中的“eject”
中的”react-scripts eject"
,然后去node_modules
中找到react-scripts
文件夹中的config
中的webpack.config.js
配置less
如果有暴露出来的话直接在根目录下的config
中找到上面所述文件进行修改即可
1 | { |
配置位置如下:
1 | npm install normalize.css --save |
安装完成后在入口文件 index.js 中引入即可。
1 | import 'normalize.css'; |
1 | npm install axios qs --save |
在根目录 public
文件夹下创建 config.js
文件
1 | window.g = { |
并下下图位置中插入此配置文件,用于后面统一修改或者统一配置请求的地址,会在 request.js
文件中使用这个配置
配置请求拦截器、响应拦截器: request.js
:
1 | import axios from 'axios'; |
管理Api文件:
请求的使用方式如下图所示:
1 | import request from '../utils/request.js' |
在某个组中使用这个接口~
1 | import { FindDictPage } from '../../apis/user'; |
1 | npm install http-proxy-middleware --save |
src
下新建 setupProxy.js
1 | const { createProxyMiddleware } = require('http-proxy-middleware'); |
1 | npm install react-router-dom --save // 我这里是"react-router-dom": "^6.3.0" |
在src
中新建utils
文件夹,并建立request.js
1 | import React from 'react'; |
然后在应用入口index.js
里引用使用这个 router.js
:
1 | import Router from './utils/router'; |
1 | npm install redux redux-thunk react-redux --save |
在 src
目录下新建 redux
文件夹,作为配置 redux
的目录:
actions:
针对不同功能模块进行配置的 actions 文件放在此目录
reducers:
针对不同功能模块进行配置的 reducers 文件放在此目录
reducers.js:
把所有 reducers 结合起来
store.js:
对 redux 的配置文件
types.js:
存放 Actions 中所需要的 type 属性值
各类文件
types.js
1 | export const MYTODO = 'MYTODO'; |
myReducer.js
1 | import { MYTODO, MYLIST } from '../types'; |
myActions.js
1 | import { MYTODO, MYLIST } from '../types'; |
otherReducer.js
1 | import { OTHERTODO, OTHERLIST } from '../types'; |
otherActions.js
1 | import { OTHERTODO, OTHERLIST } from '../types'; |
reducers.js
1 | import { combineReducers } from 'redux'; |
store.js
1 | import { createStore, applyMiddleware, compose } from 'redux'; |
以上 Redux
基本配置完成,下面是调用方法
1 | import React, { useEffect } from 'react'; |