/技术
分类:技术最近更新:2026-04-15浏览:2316
最近在做react项目时,通过懒加载做代码分割,因为架构原因就没有采用直接默认导出的形式,用函数遍历赋值React.lazy的组件代码如下:
javascript// ./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;
注意"重点问题区域"。
终端报警告信息:
bashWARNING in ./src/router/index.ts 24:15-37 Critical dependency: the request of a dependency is an expression webpack compiled with 1 warning
浏览器报错:

表示找不到对应模块(明明是可以的),然后尝试将 import(item.component) 换成 import("pages/login"),连警告Critical dependency: the request of a dependency is an expression都消失了。
经过学习,了解知识点如下:
import是静态执行的,引入的参数必须是字符串不能为变量动参
所以尝试改成这样:
javascriptimport(`${item.component}`)
结果发现虽然警告没有了,但是依旧不能识别模块,别名绝对没有问题。
然后尝试用字符串拼接:(问题解决)
javascriptimport(`@/${item.component}`)
问题解决。
!!这里需要注意,我起初一直认为是react.lazy的问题,因为官方有这样一句话:

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