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

如何让Jest识别JavaScript导入映射(import map)

解决Jest无法识别import map中"orbitcontrols"模块的问题

问题根源

Jest 基于 Node.js 运行,不支持浏览器的 <script type="importmap"> 机制,因此无法解析你通过 import map 定义的 "orbitcontrols" 这类模块别名,导致测试时出现模块解析错误。

解决方案

1. 安装本地依赖包

先通过 npm 安装 THREE.js 官方包,让测试环境能访问到本地的模块文件:

npm install three --save-dev

2. 配置 Jest 模块映射

在项目根目录的 jest.config.cjs 文件中添加 moduleNameMapper,把 import map 中的别名映射到本地安装的模块路径:

module.exports = {
  // 模拟浏览器DOM环境,适配你的页面代码
  testEnvironment: 'jsdom',
  // 对应import map的模块别名映射
  moduleNameMapper: {
    '^three$': '<rootDir>/node_modules/three/build/three.module.js',
    '^orbitcontrols$': '<rootDir>/node_modules/three/examples/jsm/controls/OrbitControls.js'
  },
  // 转换ESM模块以适配Jest的CommonJS环境
  transform: {
    '^.+\\.js$': 'babel-jest'
  }
};

若没有 jest.config.cjs 文件,直接在项目根目录新建即可。

3. 调整测试文件(可选)

你的测试文件是 .cjs 格式,建议用 CommonJS 语法规范导入模块,避免 ESM 和 CJS 混用的兼容性问题:

const fs = require('fs');
window.document.body.innerHTML = fs.readFileSync("./views/layouts/main.hbs");
// 动态导入ESM格式的业务模块
const Cube = await import("./cube.js");

4. 验证配置

重新运行测试命令:

npm test

补充说明

如果项目中还有其他通过 import map 映射的 CDN 模块,都可以沿用这套方案:先安装对应 npm 包,再在 moduleNameMapper 中添加映射规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:05:19