1 脚手架
-
CRA (常用)
- 全局安装脚手架(一次就行)
- npm i create-react-app -g
- 搭建项目
- create-react-app 项目名
- 进入项目文件夹
- cd 项目名
- 全局安装脚手架(一次就行)
-
手动建立常规文件夹
- components 项目公用组件库
- assets 项目静态资源文件夹,如img,style,第三方js,字体文件
- views/pages 项目路由对应的组件目录
- utils 项目公共封装库 如rem.js, request.js
- router 路由
- store 状态管理
2 引入组件库
-
pc - 如antd
-
app - antd-mobile(此处以该组件为例)
-
配置antd-mobile(按需引入)配置方法参考
- yarn add antd-mobile -D
- yarn add react-app-rewired customize-cra -D
- 进入package.json文件,将scripts的快捷启动命令 react-scripts 都改为 react-app-rewired
- 在项目根目录创建文件 config-overrides.js 用于修改默认配置
- yarn add babel-plugin-import -D(实现按需引入的插件)
- 在config-overrides.js文件中写入代码
const { override, fixBabelImports } = require('customize-cra'); module.exports = override( fixBabelImports('import', { libraryName: 'antd-mobile', style: 'css', }), ); -
配置完成,引用组件方式为
import { Button, WhiteSpace } from 'antd-mobile';
3 webpack 配置
3.1 配置路径别名
- 进入config-overrides.js
- 从customize-cra再引入addWebpackAlias模块,用来配置路径别名
- 配置方法
const { override, fixBabelImports, addWebpackAlias } = require('customize-cra');
const path = require('path')
function pathFn (pathUrl) {// 简化代码
return path.join(__dirname, pathUrl)
}
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd-mobile',
style: 'css',
}),
addWebpackAlias({
'@' : pathFn('./src'),
'assets' : pathFn('./src/assets'),
'components' : pathFn('./src/components'),
'router' : pathFn('./src/router'),
'utils' : pathFn('./src/utils'),
'views' : pathFn('./src/views'),
'store' : pathFn('./src/store')
})
);
3.2 sass配置
- yarn add node-sass sass-loader -D
- 若node-sass安装不上,替换下载源 yarn config set sass-binary-site npm.taobao.org/mirrors/nod…
3.3 反向代理
- 在src目录下新建文件setupProxy.js
- 安装中间件 yarn add http-proxy-middleware
- 在setupProxy.js中写入代码
- 如下使用方法为http-proxy-middleware^0.20.0版本适用,现已更新至^1.0.0版本,新版具体配置方法自行查阅文档
const proxy = require('http-proxy-middleware')
module.exports = function (app) {
app.use(proxy(
'/ajax', {
target: 'http://m.maoyan.com',//请求的域名
changeOrigin: true// 使用我们当前的http://localhost:3000来代替目标源
}
))
app.use(proxy(
'/ajax', {
target: 'http://m.maoyan.com',//请求的域名
changeOrigin: true// 使用我们当前的http://localhost:3000来代替目标源
}
))
}
到这里一个react项目的基本机构已经搭建完成,若要配置spa路由,需进一步配置
基础决定未来,一步一个脚印