本地Jest测试正常,Github Actions出现模块找不到错误求助
本地Jest测试正常,但Github Actions中找不到SVG模块的排查方案
问题现象
本地运行Jest测试套件时可正常找到导入模块并完成测试,但在Github Actions环境中运行时,出现模块找不到的错误,导致测试失败。
错误信息
src/ui/components/Icon.tsx:3:19 - error TS2307: Cannot find module '@/../public/icons/fa-bars-light.svg' or its corresponding type declarations.
3 import Svgs1 from "@/../public/icons/fa-bars-light.svg";
相关配置文件
jest.config.js
/** @type {import('ts-jest').JestConfigWithTsJest} */ const { pathsToModuleNameMapper } = require('ts-jest'); const { compilerOptions } = require('./tsconfig'); module.exports = { testEnvironment: 'jsdom', transform: { ".(ts|tsx)": "ts-jest", "^.+\.svg$": "jest-transformer-svg" // required to enable svg imports during test runs }, roots: ["<rootDir>"], moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' }), modulePaths: [compilerOptions.baseUrl], moduleDirectories: ['node_modules', 'src', 'public'] };
tsconfig.json(相关配置项)
{ "compilerOptions": { ..., "baseUrl": "./", "paths": { "@/*": [ "./src/*" ] } }, "include": [ ..., "src/**/*.ts", "src/**/*.tsx", "public/icons/*.svg" ], "exclude": [ "node_modules" ] }
目录结构
public - icons src - ui - components - Icon.tsx tsconfig.json jest.config.js
Github Action工作流
name: Node.js CI run-name: "Run Unit Tests" on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Use Node.js uses: actions/setup-node@v3 with: node-version: '18.17.1' cache: 'npm' - run: npm i - run: npm test
package.json相关依赖
{ ..., "jest-transformer-svg": "^2.0.2", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", "ts-jest": "^29.1.2", }
排查与修复方案
1. 优化模块路径映射
当前导入路径@/../public/icons/fa-bars-light.svg通过@映射到src后又用../跳出到根目录,这种写法在跨环境下可能出现解析不一致问题。
修复步骤:
- 在
tsconfig.json的paths中添加public目录的直接映射:"paths": { "@/*": ["./src/*"], "@public/*": ["./public/*"] } - 修改导入语句为:
import Svgs1 from "@public/icons/fa-bars-light.svg"; - Jest的
moduleNameMapper会自动读取tsconfig的paths配置,无需额外修改。
2. 补充SVG类型声明
错误提示提到缺少类型声明,需要为SVG文件添加TypeScript类型定义:
修复步骤:
- 在
src目录下创建types/svg.d.ts文件:declare module "*.svg" { const content: string; export default content; } - 在
tsconfig.json的include中添加类型文件路径:"include": [ ..., "src/types/**/*.d.ts" ]
3. 调整Jest路径解析规则
如果不想修改导入语句,可以直接在jest.config.js中为特殊路径添加映射:
修复步骤:
在moduleNameMapper中补充规则:
moduleNameMapper: { ...pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' }), "^@/../public/(.*)$": "<rootDir>/public/$1" }
4. 检查路径大小写一致性
Github Actions使用Linux环境,对路径大小写敏感,而本地Windows/macOS可能不敏感。需确保代码中的导入路径和实际文件的大小写完全一致。
5. 强制完整安装依赖
缓存可能导致依赖缺失,改用npm ci替代npm i,严格按照package-lock.json安装依赖:
修复步骤:
修改Github Actions工作流中的安装步骤:
- run: npm ci
内容的提问来源于stack exchange,提问作者Todd Drinkwater
相关产品推荐
相关产品推荐

