升级React项目

1,734 阅读1分钟

一、前言

技术服务于业务!如果现有项目的技术框架不算太过陈旧,并能很好支撑业务,则没有必要盲目将项目架构更新到最新版本。但本着时刻学习的心态,并且新版本框架有着更好的执行效率,在合理需求范围内,我们将更新相关项目的技术框架。

1. 相关更新框架明细

// 以下是此次我们要更新的框架,包括old Version 和 target Version

// 1. Old project version
"dependencies": {
    "antd": "2.13.11",
    "immutable": "^3.8.1",
    "moment": "^2.18.1",
    "react": "^15.5.4",
    "react-color": "^2.11.7",
    "react-dom": "^15.5.4",
    "react-redux": "^5.0.4",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.1",
    "react-router-redux": "^5.0.0-alpha.6",
    "redux": "^3.6.0",
    "redux-thunk": "^2.2.0",
    "reselect": "^3.0.1",
}
"devDependencies": {
    "webpack": "^1.14.0",
}

// 2. Target project version
"dependencies": {
    "antd": "2.13.11",
    "immutable": "^3.8.1",
    "moment": "^2.18.1",
    "react": "^16.11.0",
    "react-color": "^2.11.7",
    "react-dom": "^16.11.0",
    "react-redux": "^5.0.4",
    "react-router": "^4.1.1",
    "react-router-dom": "^4.1.1",
    "react-router-redux": "^5.0.0-alpha.6",
    "redux": "^3.6.0",
    "redux-thunk": "^2.2.0",
    "reselect": "^3.0.1",
}
"devDependencies": {
    "webpack": "^1.14.0",
}

2. 项目框架更新顺序

先核心包(react、redux等),再基础包(echarts、moment等),最后工具包(webpack等)。

二、进入升级模式

1. 核心包升级

npm install --save react@latest react-dom@latest

以下生命周期函数将在17.0版本后移除,我们需要重命名才能使用。

  • componentWillMount
  • componentWillReceiveProps
  • componentWillUpdate
cd your_project
npx react-codemod rename-unsafe-lifecycles

再使用HOOKS函数时,配置以下其eslint规则。
校验的规则:

  • 只能在最顶层使用 Hook
  • 只能在 React 函数中调用 Hook,不能在普通的 JavaScript 函数中调用 Hook
npm install eslint-plugin-react-hooks --save-dev

// 你的 ESLint 配置
{
  "plugins": [
    // ...
    "react-hooks"
  ],
  "rules": {
    // ...
    "react-hooks/rules-of-hooks": "error", // 检查 Hook 的规则
    "react-hooks/exhaustive-deps": "warn" // 检查 effect 的依赖
  }
}

2. 基础包升级

3. 工具包升级