You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest相对导入兄弟目录文件时无法定位node_modules依赖问题求解

解决方案

报错的核心原因是Jest解析../common/lib/thing.ts的第三方依赖时,默认仅从测试执行目录disp向上查找node_modules,不会主动识别common目录下的依赖包,按以下步骤修改disp/jest.config.js即可解决:

  • 新增roots配置,将common目录纳入Jest的源码扫描范围:
    roots: ["<rootDir>", "<rootDir>/../common"],
    
  • 修改moduleDirectories配置,新增common目录下的node_modules路径,让Jest可以命中common下的依赖:
    moduleDirectories: [
      "node_modules", 
      "<rootDir>/node_modules", 
      "<rootDir>/../common/node_modules"
    ],
    
  • 调整transformIgnorePatterns配置,避免Jest忽略common目录下的业务代码转译:
    transformIgnorePatterns: [
      "<rootDir>/../common/node_modules"
    ],
    
  • 如果你没有在tsconfig中配置common/*的路径映射,需要在moduleNameMapper中新增别名映射,确保能正确解析common下的业务代码:
    moduleNameMapper: {
      "^common/(.*)$": "<rootDir>/../common/lib/$1",
      // 原有其他映射规则保持不变
    }
    

配置修改完成后重启Jest即可正常运行,不需要做node_modules软链接操作。

内容的提问来源于stack exchange,提问作者Anthony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 02:54:01