使用Mocha+TypeScript测试Three.js时无法引入examples/jsm模块
Three.js示例模块(如ConvexHull)测试导入失败解决方案
问题说明
使用TypeScript+Mocha编写Three.js测试代码时,Three.js核心模块(如THREE.Vector3)可正常导入使用,但尝试导入three/examples/jsm目录下的示例模块(如ConvexHull)时,无论是CommonJS的require还是ES模块的import语法,均触发Cannot find module错误。
解决步骤
1. 明确导入路径的文件后缀
Three.js的示例JSM模块为ES模块,文件实际后缀为.js,Node.js/TypeScript在某些解析规则下需要明确指定后缀才能找到文件。修改导入语句,添加.js后缀:
// TypeScript ES模块方式 import * as THREE from 'three'; import { ConvexHull } from 'three/examples/jsm/math/ConvexHull.js';
// CommonJS方式 const THREE = require('three'); const { ConvexHull } = require('three/examples/jsm/math/ConvexHull.js');
2. 配置TypeScript模块解析规则
在项目根目录的tsconfig.json中调整编译选项,确保TypeScript能正确解析Node.js模块路径:
{ "compilerOptions": { "moduleResolution": "node", "esModuleInterop": true, "allowSyntheticDefaultImports": true, "target": "ESNext", "module": "CommonJS" // 匹配Mocha的运行环境 }, "include": ["test/**/*.ts"] }
moduleResolution: "node":让TypeScript遵循Node.js的模块解析逻辑,支持查找带后缀的ES模块esModuleInterop和allowSyntheticDefaultImports:消除ES模块与CommonJS模块之间的导入兼容性问题
3. 验证依赖版本一致性
确保package.json中three与@types/three的版本完全匹配(当前配置中两者均为0.148.0,符合要求),避免类型定义与实际模块结构不匹配导致的导入错误。
调整后的测试代码示例
import * as THREE from 'three'; import { ConvexHull } from 'three/examples/jsm/math/ConvexHull.js'; import assert from 'assert'; describe('The THREE object', function() { it('should have a defined BasicShadowMap constant', function() { assert.notEqual(THREE.BasicShadowMap, undefined); }); it('should be able to construct a ConvexHull instance', function() { const hull = new ConvexHull(); assert.ok(hull instanceof ConvexHull); }); it('should be able to construct a Vector3 with default of x=0', function() { const vec3 = new THREE.Vector3(); assert.equal(0, vec3.x); }); });
内容的提问来源于stack exchange,提问作者Jian Zhong
相关产品推荐
相关产品推荐

