umi2升级umi3的一些记录

651 阅读2分钟

因项目年代久远,使用的框架还是umi2,并存在antd3和antd4混用的情况,维护起来比较困难,所以最近在做一些框架升级依赖升级的事情,此文纯记录umi2到umi3升级过程中的一些问题。(参考链接)

package.json

{
  "devDependencies": {
     "umi": "^3.5.0"
  }
}

这里没什么好说的,我是直接升级到了v3.5.0。

升级umi-plugin-react为@umijs/preset-react

升级后并删去了无关依赖

{
    "devDependencies": {
        -  "dva": "^2.4.1",
        -  "umi-plugin-ga": "^1.1.3"
    }
}

然后由于 Umi 3 的配置方式是拍平的方式,还需要修改配置。

export default {
- plugins: [
-   ['umi-plugin-react', {
-     dva: {},
-     antd: {},
-     ...
-   }]
- ],
+ dva: {},
+ antd: {},
+ ...
}

注意:

  1. 无需重复注册插件,Umi 3 会自动注册依赖中的 Umi 插件
  2. 配置提取到外面

功能变化:

  • 删除了 routes、library、dll、hardSource、pwa、hd、fastClick、chunks,不可继续使用
  • 内置 dynamicImport、title、scripts、headScripts、metas 和 links 到 Umi 中,可继续使用
  • 其他功能不变

配置层修改

  • 删除treeshaking: true,已内置无需重复设置
  • 删除 minimizer,只保留 terserjs
  • 删除 uglifyJSOptions,没有必要
  • 修改 lessLoaderOptions 命名为 lessLoader
  • terserJSOptions改为terserOptions
  • 删除 disableRedirectHoist,始终不再做 redirect hoist
  • cssLoaderOptions改为cssLoader
  • 删除 sass,不再支持,后续会以插件的方式提供
  • 删除pwa

以上是我涉及到的修改。

代码层

import all from umi

不再保留umi/xxx的接口,全部从umi中import 例:

- import { formatMessage } from "umi-plugin-react/locale";  
+ import { formatMessage } from "umi"; 

- import router from "umi/router"; 
+ import { history } from "umi";

- import Link from 'umi/link';
+ import { Link } from 'umi';

umi/router 改为history代替

- import router from 'umi/router';
+ import { history } from 'umi';

- router.push('/foo');
+ history.push('/foo');

CSS 里引用别名或三方库,需要加前缀

遇到的问题

class组件国际化问题

import { injectIntl } from "umi";
class Index extends Component {
...
    const {
      intl: { formatMessage },
    } = this.props;
...
return <div>formatMessage({ id: xxx })</div>
...
}
export default injectIntl(Index);

mfsu报错 Module not found

完整报错如下

image.png 出现原因:当在 .mjs 文件或其他 .js 文件中导入模块,并且它们最近的 package.json 中包含 “type” 字段,且值为 "module"时。引用文件的时候需要包含扩展名,否则 webpack 会提示 Module not found 的错误且编译失败。(事实上大部分是node_modules中依赖相互引用的问题)

解决方法:关闭fullySpecified

image.png

在chainWebpack中添加下面的配置就可以正常使用mfsu啦。

  config.module
    .rule("mjs-rule")
    .test(/.m?js/)
    .resolve.set("fullySpecified", false);

AssertionError [ERR_ASSERTION]: chunk of umi not found

删除src/.umi,删除node_modules&lock文件,重新install