在Turborepo+Yarn Workspaces中配置Jest的transformIgnorePatterns遇阻
Turborepo + Yarn Workspaces 下 Jest 配置问题解决方案
验证路径匹配正确性的方法
- 打印生成的正则表达式:在
jest.config.ts中添加代码输出最终路径字符串,对比实际包路径是否符合预期:const targetPattern = `${path.join(__dirname, "../..")}/node_modules/(?!(oauth4webapi))`; console.log('Transform ignore pattern:', targetPattern); // 运行Jest时查看控制台输出,确认路径是否指向项目根目录的node_modules - 编写正则测试脚本:单独创建测试文件,验证实际路径的匹配结果:
import path from 'path'; const rootNodeModules = path.join(__dirname, '../..', 'node_modules'); const testPaths = [ `${rootNodeModules}/oauth4webapi/index.js`, `${rootNodeModules}/lodash/index.js` ]; const regex = new RegExp(`${rootNodeModules}/(?!oauth4webapi)`); testPaths.forEach(p => { console.log(`${p} -> ${regex.test(p)}`); // 预期:oauth4webapi路径返回false(不被忽略),其他包返回true(被忽略) }); - 查看Jest调试日志:执行Jest命令时添加
--debug参数,日志会输出文件处理详情,可直接确认oauth4webapi的文件是否被正确排除在忽略列表外。
Yarn Workspaces 适配的 Jest 配置
Yarn Workspaces的依赖结构与pnpm不同,可通过以下方式调整配置:
- 使用Jest内置的
<rootDir>变量
手动指定rootDir为项目根目录,再用相对路径编写正则,避免绝对路径拼接的问题:
// jest.config.ts
import path from 'path';
export default {
rootDir: path.join(__dirname, '../..'),
transformIgnorePatterns: [
'
],
// 其他Jest配置
};
2. **简化相对路径正则** 如果无需严格限定根目录的`node_modules`,可直接使用通用正则,适配Yarn的依赖查找逻辑: ```typescript transformIgnorePatterns: [ 'node_modules/(?!oauth4webapi)' ]
注:该正则会匹配所有层级的
node_modules,若子包存在独立的oauth4webapi依赖,也会被排除在忽略列表外。
补充注意事项:
- 确保项目已配置正确的转换器(如
babel-jest),否则即使排除了忽略列表,也无法正确转译oauth4webapi的代码。 - Yarn Workspaces默认会在根目录共享依赖,因此只需确保根目录的
oauth4webapi被正确处理即可。
内容的提问来源于stack exchange,提问作者wongx
相关产品推荐
相关产品推荐

