8

react 高效高质量搭建后台系统 系列 —— 脚手架搭建 - 彭加李

 1 year ago
source link: https://www.cnblogs.com/pengjiali/p/16999119.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

其他章节请看:

react 高效高质量搭建后台系统 系列

脚手架搭建

本篇主要创建新项目 myspug,以及准备好环境(例如:安装 spug 中用到的包、本地开发和部署、自定义配置 react-app-rewired、代理 http-proxy-middleware、babel),为后续搭建真正的框架打好基石。

:许多细节前面我们已经研究过,这部分就不在冗余介绍,请看相关链接。

创建新项目

详情请看 这里

Create React App 是一个用于学习 React 的舒适环境,也是用 React 创建新的单页应用的最佳方式。

$ npx create-react-app myspug
$ cd myspug/
$ npm start

访问 http://localhost:3000 即可看到 react 的页面。就像这样:

react-cli-demo-1.jpeg

myspug 目录结构如下:

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----          2022/3/3     17:50                node_modules
d-----          2022/3/3     17:48                public
d-----         2022/3/18     19:22                src
-a----        1985/10/26     16:15            310 .gitignore
-a----          2022/3/3     17:49        1120931 package-lock.json
-a----          2022/3/3     17:49            817 package.json
-a----        1985/10/26     16:15           3359 README.md
  • public 中最重要的是 index.html,即单页面
  • src/index.js 是入口文件,里面引用着 src/App.js 组件。

安装依赖包

我们根据 spug/packages.json 的内容,选择性的安装自己所需要的软件包。

// spug/packages.json
{
  "name": "spug_web",
  "version": "3.0.0",
  "private": true,
  "dependencies": {
    // icon
    "@ant-design/icons": "^4.3.0",
    // 图表相关
    "@antv/data-set": "^0.11.8",
    // Ace 是一个用 JavaScript 编写的代码编辑器。 (不用)
    "ace-builds": "^1.4.13",
    // ui
    "antd": "^4.19.2",
    // http
    "axios": "^0.21.0",
    // 图表
    "bizcharts": "^3.5.9",
    // 小型功能路由器,通过搜索 `Enroute({` 发现只在 Test.js 中使用,应该是用于测试(不用)
    "enroute": "^1.0.1",
    // 路由相关
    "history": "^4.10.1",
    // jquery (不用)
    "jquery": "^3.6.0",
    "lodash": "^4.17.19",
    // 状态
    "mobx": "^5.15.6",
    "mobx-react": "^6.3.0",
    // 日期库
    "moment": "^2.24.0",
    // 数字
    "numeral": "^2.0.6",
    "react": "^16.13.1",
    // 与 ace Editor 相关(不用)
    "react-ace": "^9.5.0",
    // react
    "react-dom": "^16.13.1",
    // 路由
    "react-router-dom": "^5.2.0",
    "react-scripts": "3.4.3",
    // 浏览器中使用终端(不用)
    "xterm": "^4.6.0",
    "xterm-addon-fit": "^0.5.0"
  },
  // 本地启动、打包
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  },
  // eslint 相关。查找并修复JavaScript代码中的问题。
  "eslintConfig": {
    "extends": "react-app"
  },
  // 编译后的源码支持的浏览器。不用动
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },

  "devDependencies": {
    // 用于支持 es6 中装饰器的语法
    "@babel/plugin-proposal-decorators": "^7.10.5",
    "anywhere": "^1.5.0",
    "bx-tooltip": "^0.1.6",
    // 新的 [email protected] 版本的关系,你还需要安装 customize-cra
    "customize-cra": "^1.0.0",
    // http 代理中间件
    "http-proxy-middleware": "0.19.2",
    "less": "^3.12.2",
    "less-loader": "^7.1.0",
    "mockjs": "^1.1.0",
    // 一个对 create-react-app 进行自定义配置的社区解决方案
    "react-app-rewired": "^2.1.6"
  }
}

笔者安装如下软件包:

// ui
$ npm i antd
// 状态管理
$ npm i mobx mobx-react
// http
$ npm i axios
// 路由
$ npm i react-router-dom@5
// icon
$ npm i @ant-design/icons
// 修改配置文件
$ npm i -D react-app-rewired customize-cra
// css 预编译
$ npm i -D less less-loader
// bebel 相关
$ npm i -D @babel/plugin-proposal-decorators@7
// mock 数据
$ npm i -D mockjs@1
// 图表
$ npm i bizcharts@3
$ npm i @antv/data-set
// 路由相关
$ npm i history@4
// js 工具库
$ npm i lodash
// 日期
$ npm i moment
// 数字
$ npm i numeral

Tip:如果安装失败可以这样:

  • 每次安装一个包
  • 切换安装包的版本
  • 再次尝试,有时候第二遍就成功
  • 回家尝试,公司安装失败,家里可能安装成功

至此,对比 spug 和 myspug 的 package.json,有如下差异以及一些未完成项:

  • myspug 没有jquery、ace-builds、react-ace、enroute、xterm、xterm-addon-fit,因为笔者不需要。
  • bx-tooltip 视后面需求是否安装
  • scripts,用于启动项目或编译项目。spug 中使用的是 react-app-rewired,而 myspug 使用的是 react-scripts。下文配置。
  • http-proxy-middleware 未安装,代理相关。下文安装并配置
  • eslintConfig 配置,eslint 相关。两者几乎相同,不管它。
  • browserslist 配置,编译后的源码支持的浏览器。两者相同,不管它。

antd 按需引入 css

详情请看 这里

spug 中使用的是 react-app-rewired,而 myspug 使用的是 react-scripts。

react-app-rewired 是一个对 create-react-app 进行自定义配置的社区解决方案。

react-app-rewired 的引入是作为 antd 按需引入 css 解决方案的一部分。

步骤如下:

  • 安装 react-app-rewired 和 customize-cra(上文已安装)
  • 安装 babel-plugin-import
  • 修改 package.json,通过 react-app-rewired 来启动、打包和测试
/* package.json */
"scripts": {
-   "start": "react-scripts start",
+   "start": "react-app-rewired start",
-   "build": "react-scripts build",
+   "build": "react-app-rewired build",
-   "test": "react-scripts test",
+   "test": "react-app-rewired test",
}
  • 项目根目录创建一个 config-overrides.js(内容请看链接) 用于修改默认配置
  • 修改 App.js 用于验证 antd 样式按需引入是否生效
// E:\myspug\src\App.js
import { Button } from 'antd';

export default function App() {
    return (
        <div className="App">
            <Button type="primary">Primary Button</Button>
        </div >
    );
}
  • 最后启动服务 npm run start,浏览器访问 http://localhost:3000/,看见一个蓝色按钮说明成功。

Tip: 笔者遇到如下报错,经尝试发现点击antd.css(@import '~antd/dist/antd.css';)报错,怀疑包下载有问题,最后卸载 antd,再次安装 antd@4即可。

Compiled with problems:X

ERROR in ./src/App.js 3:0-34

Module not found: Error: Can't resolve 'antd/es/button/style/css' in 'E:\myspug\src'

详细介绍 这里

代理后续或许会用得到,我们先配置它。

Tip:笔者这版的react脚手架默认已有 http-proxy-middleware(http 代理中间件),所以我们无需重复下载

步骤如下:

  • 新建 setupProxy.js 用于配置
// src/setupProxy.js

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
  app.use(
    // 将原来的 proxy 改为 createProxyMiddleware 
    createProxyMiddleware(
      '/pengjiali',
      {
        target: 'https://www.cnblogs.com/',
        changeOrigin: true
      }
    )
  )
}
  • 创建一个组件(HelloWorld.js)并在 App.js 中引入
const axios = require('axios');

export default function HelloWorld() {
    axios.get('/pengjiali/p/14561119.html')
        .then(function (response) {
            // handle success
            console.log(response.data);
        }).catch(function (error) {
            // handle error
            console.log(error);
        })

    return <div>hello world2!</div>
}
  • 重启服务,控制台输出博文内容,说明代理生效。

Tip:初次运行 require('axios') 报错,将 axios 卸载,安装和 spug 中相同的版本 npm i axios@0 即可。

babel

例如 es11 中有 BigInt、可选链操作符( ?. )、空值合并操作符(??),spug 是否会将 ?. 编译,在低版本浏览器中运行呢?

在 spug 中 package.json 中与 babel 相关的单词只有 @babel/plugin-proposal-decorators(后续讲状态管理 mobx 时一起介绍),也就是用于支持装饰器。

由于后台系统通常可以指定浏览器版本,笔者就不展开。

Tip:感兴趣的朋友可以自行提取 spug 项目的 webapck 配置查看。这个过程是不可逆的。

其他章节请看:

react 高效高质量搭建后台系统 系列


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK