编程知识 cdmana.com

Summary of upgrading Ant Design Pro V2 to V4

Preface

Not long ago, I took over a project with a long history (shi) Objective (shan), The complexity of the technology stack ( confusion ) It made me cry : You can even use the front three frameworks in a project (Angular1, Vue, React).

Three copies of the code , It should have brought me more happiness , But why did it happen ?

In view of the new demand received , So I once again introduced Ant Design Pro V4 Family bucket ( The fourth happiness ).Hooks and Ant Design V4 The collocation of , It's really delicious to use , In especial Form Form rewriting , Greatly improved development efficiency . So I took advantage of my spare time , I decided to take responsibility for one of my own Ant Design Pro V2 The project has also been upgraded to V4 edition .

This is to record the upgrade process .

UMI3 upgrade

I was using ant-design-pro 2.2.0 The scaffold Generated front end project (JS edition , Not TS edition ), It uses umi@2 and antd@3. therefore , First of all, put UMI Upgrade to the latest V3 edition .

Refer to official documentation :

  1. 《 Quickly upgrade to umi@3》
  2. 《 upgrade antd pro The project to umi@3》

a. Delete package.json Inside dva and umi-plugin The plug-in at the beginning , Change to "umi": "^3.0.0" and "@umijs/preset-react": "^1.2.2"

among @umijs/preset-react Has included the previous umi-plugin plug-in unit

{
  "dependencies": {
-   "dva": "^2.6.0-beta.16",
  },
  "devDependencies": {
-   "umi": "^2.13.0",
-   "umi-types": "^0.5.9"
-   "umi-plugin-react": "^1.14.10",
-   "umi-plugin-ga": "^1.1.3",
-   "umi-plugin-pro": "^1.0.2",
-   "umi-plugin-antd-icon-config": "^1.0.2",
-   "umi-plugin-antd-theme": "^1.0.1",
-   "umi-plugin-pro-block": "^1.3.2",
+   "umi": "^3.0.0",
+   "@umijs/preset-react": "^1.2.2"
  }
}

perform npm install reinstall

In the process of practice, we found that :

You need to update antd@3 To latest edition :npm i antd@3.26.20

reinstall npm i redux react-redux

b. modify config/config.js The configuration file

Originally, we exported an object directly :

export default {

}

Now change to :

import { defineConfig } from 'umi';

export default defineConfig({

})

Delete obsolete attributes : plugins and disableRedirectHoist

Delete devtool Configuration of , Just use the default configuration

It is roughly changed to the following format :

import { defineConfig, utils } from 'umi';

const { winPath } = utils;

export default defineConfig({
  //  adopt  package.json  Automatically mount  umi  plug-in unit , No need to mount again 
  // plugins: [],
  antd: {},
  dva: {
    hmr: true,
  },
  locale: {
    default: 'zh-CN',
    baseNavigator: true,
  },
  dynamicImport: {
    //  There is no need to  level, webpackChunkName  To configure 
    // loadingComponent: './components/PageLoading/index'
    loading: '@/components/PageLoading/index',
  },
  //  Temporarily closed 
  pwa: false,
  lessLoader: { javascriptEnabled: true },
  cssLoader: {
    //  there  modules  Acceptable  getLocalIdent
    modules: {
      getLocalIdent: (context, localIdentName, localName) => {
        if (
          context.resourcePath.includes('node_modules') ||
          context.resourcePath.includes('ant.design.pro.less') ||
          context.resourcePath.includes('global.less')
        ) {
          return localName;
        }
        const match = context.resourcePath.match(/src(.*)/);
        if (match && match[1]) {
          const antdProPath = match[1].replace('.less', '');
          const arr = winPath(antdProPath)
            .split('/')
            .map(a => a.replace(/([A-Z])/g, '-$1'))
            .map(a => a.toLowerCase());
          return `antd-pro${arr.join('-')}-${localName}`.replace(/--/g, '-');
        }
        return localName;
      },
    }
  }
})

c. Module import mode changed

//  Import mode changed 
- import Link from 'umi/link';
- import { connect } from 'dva';
- import { getLocale, setLocale, formatMessage } from 'umi-plugin-react/locale';
+ import {
+   Link,
+   connect,
+   getLocale,
+   setLocale,
+   formatMessage,
+ } from 'umi';


//  Route jump mode changed 
- import { router } from 'umi';
+ import { history } from 'umi';
- router.push()
+ history.push()

d. Routing configuration modification

umi2 in , Privilege routing is configuration Routes attribute . stay umi3 in , It was changed to wrappers attribute .

modify config/router.config.js

export default [
  // app
  {
    path: '/',
    component: '../layouts/BasicLayout',
    wrappers: ['../pages/Authorized'], // Routes  Turned into  wrappers
    routes: [],
  },
];

e. Restart project

npm run start Theoretically , Projects should be able to be umi3 It's on .

If you still report an error , Then modify the code according to the cause of the error .

Ant Design Pro Built in component upgrades

Ant Design Pro v2 Scaffolding provides Layout Components , Has been pulled apart into a single npm package @ant-design/pro-layout. At the same time, the government also encapsulates several commonly used components , Convenient and rapid business development , See ProComponents Official website .

But in my original project Layout The component function is enough for the time being , Considering the big changes in the code , Therefore, the component has not been upgraded for the time being .

Ant Design 4 upgrade

Refer to official documentation : 《 from v3 To v4》

a. antd Upgrade to 3.x The latest version ( We are already upgrading umi3 The process has been upgraded antd), Follow the console warning Information removal / Modify the relevant API

b. Upgrade project React 16.12.0 above npm i react@^16.12.0

Rerun the project , See if it works correctly

c. Use command line tools to quickly upgrade

because antd4 Refactoring a lot of components , In order to be compatible with existing antd2 Discarded components ( Like the old version of Form), The official provided @ant-design/compatible This npm package

import { Form, Mention } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';

Officials provided one cli Tools , Can automatically convert the way code is introduced . Running cli front , Please submit your local code modification first .

#  Go into old projects 
cd myproject
#  adopt  npx  Direct operation 
# src  Is the front-end source code directory folder 
npx -p @ant-design/codemod-v4 antd4-codemod src

For parts that cannot be modified automatically ,codemod Will prompt at the command line , It is recommended to modify it manually according to the prompts . After modification, you can run the above command repeatedly to check .

d. upgrade antd edition

npm i antd@^4.0.0 @ant-design/icons@^4.0.0 @ant-design/compatible@^1.0.0

After successful installation , Restart project , View page effects .

Problems after upgrading

a. The styling

The updated history code ,Form Components refer to @ant-design/compatible,class The class name has changed , from ant-form Turned into ant-legacy-form. If you change the style of this part in your project , You need to manually modify the class name .

Style problems can only rely on their own page to check ...

b. API problem

//  Old edition 
<TextArea autosize={{ minRows: 5 }} />

//  new edition 
<TextArea autoSize={{ minRows: 5 }} />

such api The change of , Can only rely on manual modification and page error to modify ...

c. antd4 Self bug

such as RangePicker attribute defaultPickerValue Invalid

There are risks to upgrading , Dig a hole carefully !

summary

The upgrade process is much easier than I expected , But it's not much on the project page ( Only 20 Multiple pages ), At the beginning, I built the bottom frame ( The system is more familiar with ) Under the premise of .

In the preface, I mentioned the application of the stone left over from history , In fact, it is in a precarious situation , It's going to be out of maintenance . Even if I introduce the latest technology stack , But a few years later , Those who take over will certainly make complaints about it :Antd pro 4 This version is too old !

In recent years, the market has also put forward Microfront The concept of , The corresponding micro front end framework single-spa,qiankun It also came into being .

Look at the maintenance of the hands of the various technology stack code , I remember a famous saying :

There is no micro front end in the world , There are more people blowing , And it becomes KPI. I write code is jQuery A shuttle ! ——— Lu xun

版权声明
本文为[Crimson]所创,转载请带上原文链接,感谢

Scroll to Top