Yarn工作区中Semver的LRU不是构造函数的测试报错问题
问题解决:Yarn工作区执行
yarn test报TypeError: LRU is not a constructor 错误详情
执行yarn test时触发以下报错:
TypeError: LRU is not a constructor at Object.<anonymous> (../node_modules/semver/classes/range.js:202:15) at Object.<anonymous> (../node_modules/semver/classes/comparator.js:141:15) at Object.<anonymous> (../node_modules/semver/index.js:29:20) at _jestSnapshot (../node_modules/@jest/expect/build/index.js:15:16) at createJestExpect (../node_modules/@jest/expect/build/index.js:30:28) at Object.<anonymous> (../node_modules/@jest/expect/build/index.js:39:20)
问题根源
核心是依赖版本不兼容:
semver@7.6.0依赖的lru-cache版本范围为^6.0.0 || ^7.0.0 || ^8.0.0 || ^9.0.0,它预期的是CommonJS风格导出(直接require('lru-cache')即可获取构造函数)。- 你安装的
lru-cache@10.2.0是ESM优先版本,在CommonJS环境中必须通过require('lru-cache').default才能拿到构造函数,导致semver调用时直接失败。
解决方案
1. 降级lru-cache到兼容版本
在webapp目录执行命令,锁定lru-cache到v9.x稳定版:
yarn add lru-cache@^9.1.2 --dev
2. 清理缓存并重新安装依赖
# 清除Yarn全局缓存 yarn cache clean # 重新安装所有工作区依赖 yarn install
3. 强制锁定依赖版本(可选)
为避免后续版本冲突,可在根目录package.json中添加resolutions字段,强制所有工作区使用指定版本的lru-cache:
{ "private": true, "workspaces": [ "webapp" ], "packageManager": "yarn@4.1.1", "dependencies": { "@jest/expect": "^29.7.0", "semver": "^7.6.0" }, "resolutions": { "lru-cache": "^9.1.2" } }
额外注意事项
- 不要在根目录和webapp目录重复安装semver,保持依赖层级清晰,避免版本冲突。
- 检查jest配置中的
moduleDirectories,确保优先加载当前工作区的node_modules,防止跨工作区的依赖版本混乱。
内容的提问来源于stack exchange,提问作者Omar Imtiaz
相关产品推荐
相关产品推荐

