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

Jest moduleNameMapper修复export报错后致@mswjs导入失败的解决问询

解决create-react-app + ts-jest 引入microsoft-cognitiveservices-speech-sdk的Jest错误方案

问题根源

microsoft-cognitiveservices-speech-sdk依赖的uuid包使用ES模块语法,Jest默认未转译导致Unexpected token 'export';但全局映射uuid到CommonJS版本会覆盖@mswjs/utils/uuid的内部实现,引发uuidv4 is not a function冲突。

可行配置方案

  1. 精准映射uuid,避免全局覆盖
    修改jest.config.js(或package.json中的jest字段)的moduleNameMapper,仅针对microsoft-cognitiveservices-speech-sdk依赖的uuid做映射,同时排除@mswjs下的uuid模块:

    moduleNameMapper: {
      // 仅映射speech-sdk依赖的uuid到CommonJS版本
      '^uuid$': '<rootDir>/node_modules/uuid/dist/index.cjs',
      // 保留@mswjs内部的uuid实现,不做映射
      '^@mswjs/utils/uuid$': '@mswjs/utils/uuid'
    }
    
  2. 调整转译规则,让Jest处理speech-sdk
    更新transformIgnorePatterns,将microsoft-cognitiveservices-speech-sdk和uuid加入转译白名单,确保Jest转译这两个包的ES模块:

    transformIgnorePatterns: [
      'node_modules/(?!(microsoft-cognitiveservices-speech-sdk|uuid)/)'
    ]
    
  3. 确保ts-jest配置正确
    如果使用自定义ts-jest配置,确认基础配置无误:

    preset: 'ts-jest',
    testEnvironment: 'jsdom',
    transform: {
      '^.+\\.tsx?$': 'ts-jest'
    }
    
  4. 清理Jest缓存
    执行命令清除旧缓存,避免配置不生效:

    npx jest --clearCache
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 09:58:28