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

SharePoint Framework中ts-jest无法处理自建包文件的问题

解决SPFx中ts-jest无法转译自建包的问题

核心问题分析

自建包project-room-base的入口JS文件未被ts-jest正确转译,即使转成CommonJS后,其依赖文件仍出现相同警告,本质是ts-jest未对该包内的JS/TS文件执行完整转译流程。

具体解决步骤

1. 强制ts-jest处理自建包的JS/TS文件

修改Jest配置,明确指定所有JS、TS文件都通过ts-jest转译,替换原有的transform配置:

const { createJsWithTsPreset } = require('ts-jest')
module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'node',
  transformIgnorePatterns: ['/node_modules/(?!project-room-base/)'],
  verbose: true,
  transform: {
    '^.+\\.(ts|tsx|js|jsx)$': 'ts-jest',
  },
};

这样确保自建包内的JS入口文件和依赖的TS/JS文件都被ts-jest处理。

2. 检查自建包的编译配置

确保自建包的tsconfig.json满足以下要求:

  • outDir不能设为''或.,必须指定单独的输出目录(如lib)
  • module设置为commonjs(适配Node/Jest的模块解析)
  • package.json中main字段指向编译后的入口文件(如lib/index.js)
  • 自建包的include字段覆盖所有需要编译的源码文件,示例:
{
  "compilerOptions": {
    "outDir": "lib",
    "module": "commonjs",
    // 其他配置...
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "lib"]
}

3. 修正transformIgnorePatterns正则

确保正则表达式准确匹配需要排除的node_modules目录,仅让自建包跳过忽略:

transformIgnorePatterns: ['/node_modules/(?!project-room-base/)']

避免因正则写法错误导致自建包仍被忽略转译。

4. 清理Jest缓存

修改配置后执行以下命令清理缓存,避免旧缓存影响测试:

jest --clearCache

5. 验证版本兼容性

确保ts-jest版本与项目使用的TypeScript版本(由@microsoft/rush-stack-compiler-4.7管理的4.7.x)兼容,建议使用ts-jest@28.x版本(支持TS 4.5-4.9)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:40:19