Skip to content

Cannot 查找模块

错误信息

                Cannot 查找模块 './utils' or 它的 corresponding 类型 declarations
              

快速摘要

Jest 能't 查找模块你're trying 到导入. path 可能是 错误, file 可能不 exist, or Jest's 模块 resolution isn't 配置正确地.

为什么发生

  • 导入 path 是错误 — typo in file path or 不正确相对 path.

  • 模块 file doesn't exist or 有不同 name.

  • Jest's moduleNameMapper 是不 配置 for path aliases.

  • file extension doesn't match 什么 Jest expects.

最小示例

✗ 错误代码
// File is at ./src/utils.js but imported as ./utils
const { add } = require('./utils'); // Cannot find module
✓ 修复代码
// Correct path
const { add } = require('./src/utils');

Fix 导入 path 到 match 实际 file 位置.

如何诊断

  • 检查导入 path — 是 file actually at 那个位置?

  • 验证 file exists and 有正确 name.

  • 如果 using path aliases (如 @/utils), 检查 Jest's moduleNameMapper 配置.

  • 检查如果 file extension 是正确 (.js, .ts, .jsx, .tsx).

如何修复

  • Fix 导入 path 到点 到正确 file 位置.

  • 创建 missing 模块 file.

  • 配置 moduleNameMapper in jest.配置.js for path aliases.

  • Ensure file extension matches Jest's testMatch or moduleFileExtensions 配置.

如何预防

  • Use consistent 导入 paths and path aliases.

  • 配置 Jest's moduleNameMapper 到 match 你的构建 tool's path aliases.

相关资源

相关课程

← 返回语言