使用importmap时TS2307模块未找到错误的配置方案咨询
解决Three.js + TypeScript + Import Map子模块TS2307错误
步骤1:安装Three.js类型依赖
先确保已安装官方维护的Three.js类型声明:
npm install @types/three --save-dev
步骤2:配置HTML中的Import Map
在入口HTML文件里补全子模块的映射路径,确保指向本地服务器可访问的文件:
<script type="importmap"> { "imports": { "three": "/node_modules/three/build/three.module.js", "three/examples/jsm/controls/OrbitControls": "/node_modules/three/examples/jsm/controls/OrbitControls.js", "three/examples/jsm/libs/stats.module": "/node_modules/three/examples/jsm/libs/stats.module.js", "three/examples/jsm/libs/lil-gui.module": "/node_modules/three/examples/jsm/libs/lil-gui.module.js" } } </script>
注意:路径要和Express服务器静态资源配置对应,确保服务器能读取node_modules下的文件。
步骤3:配置Express静态资源访问
在Express服务器代码中添加静态资源目录,允许访问node_modules:
import express from 'express'; const app = express(); // 暴露node_modules目录,供importmap加载模块 app.use(express.static('node_modules')); // 暴露你的项目静态文件目录(比如public) app.use(express.static('public')); app.listen(3000, () => console.log('Server running on http://localhost:3000'));
步骤4:修改tsconfig.json让TypeScript识别映射
在tsconfig.json中配置paths和模块解析规则,让TypeScript能找到子模块的类型声明:
{ "compilerOptions": { "target": "ESNext", "module": "ESNext", "moduleResolution": "bundler", // 适配importmap的解析逻辑 "baseUrl": ".", "paths": { "three": ["./node_modules/@types/three"], "three/examples/jsm/controls/OrbitControls": ["./node_modules/@types/three/examples/jsm/controls/OrbitControls"], "three/examples/jsm/libs/stats.module": ["./node_modules/@types/three/examples/jsm/libs/stats.module"], "three/examples/jsm/libs/lil-gui.module": ["./node_modules/@types/three/examples/jsm/libs/lil-gui.module"] }, "typeRoots": ["./node_modules/@types"], "strict": true // 可选,根据项目需求调整 }, "include": ["src/**/*"] // 你的TypeScript文件目录 }
正确的导入方式
完成上述配置后,即可正常导入子模块:
import * as THREE from 'three'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; import Stats from 'three/examples/jsm/libs/stats.module'; import { GUI } from 'three/examples/jsm/libs/lil-gui.module';
内容的提问来源于stack exchange,提问作者Bernd von Platen
相关产品推荐
相关产品推荐

