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

Jest无法解析带参数的模块导入,寻求解决方案

解决Jest无法解析带参数的core-js导入问题

问题描述

运行Jest测试时出现以下错误:

Cannot find module 'core-js/modules/es.array.flat#?./my-file-path' from 'src/some-of-my-files.js'

Require stack:

> 1 | import "core-js/modules/es.array.flat#?./my-file-path";
    | ^
  at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:324:11)

Jest无法解析这类带#?参数的导入语句,当前jest.config.js配置如下:

module.exports = {
  moduleNameMapper: {
    // some mappers
  },
  setupFiles: [
    // some files
  ],
  setupFilesAfterEnv: [
    // some files 
  ],
  transform: {
    "^.+\\.(js|jsx)$": "babel-jest"
  },
  transformIgnorePatterns: [
    '/node_modules/(?!some-module-name)(.*)'
  ],
  testEnvironment: "jsdom",
  testPathIgnorePatterns: ["/test.js"]
};

解决方案

方案1:通过moduleNameMapper匹配带参数的导入

在moduleNameMapper中添加正则规则,匹配带#?后缀的core-js模块,将其映射到实际的core-js模块路径:

module.exports = {
  // ...其他配置
  moduleNameMapper: {
    // 保留原有映射,新增以下规则
    '^core-js/modules/(.*)\\?.*$': '<rootDir>/node_modules/core-js/modules/$1'
  },
  // ...其他配置
};

该规则会把类似core-js/modules/es.array.flat#?./my-file-path的导入替换为core-js/modules/es.array.flat,让Jest能正确定位模块文件。

方案2:调整Babel配置避免生成带参数的导入

如果这类导入是Babel自动注入的,可检查项目的Babel配置(如.babelrc或babel.config.js):

  • 确保使用@babel/preset-env的useBuiltIns: 'usage'或entry模式时,配置了正确的corejs版本,避免生成带参数的导入语句。
  • 也可以在项目入口文件手动导入完整的core-js polyfill,替代自动注入:
// 项目入口文件(例如src/index.js)
import 'core-js/stable';
import 'regenerator-runtime/runtime';

方案3:确认core-js已正确安装

若项目未安装core-js或版本不匹配,执行以下命令安装对应版本:

npm install core-js@3 --save
# 或使用yarn
yarn add core-js@3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:30:44