import引入报”Critical dependency: the request of a dependency is an expression“

分类:前端来源:站内 最近更新:2022-08-13 11:40:53浏览:1428留言:0

最近在做react项目时,通过懒加载做代码分割,因为架构原因就没有采用直接默认导出的形式,用函数遍历赋值React.lazy的组件代码如下:

// ./src/router/index.ts
import routerData from "./router_data";
import { lazy } from "react";
// 遍历路由地址去除组件部分
const lazycomps = (data: any[]) => {
  return data.map((item) => {
    let _item = { ...item };
    if (_item.component) {
      _item.component = lazy(() => import(item.component)); //重点问题区域
    }
    if (_item.children) {
      _item.children = lazycomps(_item.children);
    }
    return _item;
  });
};

const routerList = lazycomps(routerData);
export default routerList;

const routerList = lazycomps(routerData);
export default routerList;

注意"重点问题区域"。

终端报警告信息:

WARNING in ./src/router/index.ts 24:15-37
Critical dependency: the request of a dependency is an expression

webpack compiled with 1 warning

浏览器报错

WX20220813-112647.png

表示找不多对应模块(明明是可以的),然后尝试 import(item.component)换成 import("pages/login"),连警告"Critical dependency: the request of a dependency is an expression"都消失了。

经过学习,了解知识点如下:

import是静态执行的,引入的参数必须是字符串不能为变量动参

所以尝试改成这样

import(`${item.component}`)

结果发现虽然警告没有了,按时依旧不能识别模块,别名绝对没有问题。

然后尝试用字符串拼接:(问题解决)

import(`@/${item.component}`)

解决问题。

!!这里需要注意,我起初一直认为是react.lazy的问题,因为官方有这样一句话:

WX20220813-113916.png

"React.lazy 目前只支持默认导出(default exports)"。我一直往这上面花了好久的时间去做容错处理,结果是import静态参数的问题。



0

发表评论

评论列表(0)

  • 暂时没有留言
热门