加载GLB格式3D模型时遭遇three模块解析错误求助
问题排查与解决方案
1. 模块引入错误修复
控制台报错是因为浏览器无法解析裸模块名"three",ES模块要求必须使用相对/绝对路径或完整CDN URL。
方案一:使用CDN ES模块
在index.html中添加importmap配置,让浏览器能识别three相关模块:
<script type="module" src="./3dmodel.js"></script> <script type="importmap"> { "imports": { "three": "https://unpkg.com/three@0.160.0/build/three.module.js", "three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/" } } </script>
之后在3dmodel.js中正常导入即可:
import * as THREE from 'three'; import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
方案二:本地依赖导入
先通过npm安装three:
npm install three
再在3dmodel.js中使用相对路径导入(假设node_modules在项目根目录):
import * as THREE from '../node_modules/three/build/three.module.js'; import { GLTFLoader } from '../node_modules/three/examples/jsm/loaders/GLTFLoader.js';
2. 将模型加载到main-title区域
修改3dmodel.js代码,把渲染器挂载到目标元素:
// 获取目标容器 const container = document.querySelector('.main-title'); // 若元素是id则用#main-title // 初始化three核心组件 const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, container.clientWidth / container.clientHeight, 0.1, 1000); const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); // 适配容器尺寸 renderer.setSize(container.clientWidth, container.clientHeight); renderer.setPixelRatio(window.devicePixelRatio); container.appendChild(renderer.domElement); // 加载GLB模型 const loader = new GLTFLoader(); loader.load('spaceship.glb', (gltf) => { scene.add(gltf.scene); // 调整模型位置与缩放(按需修改) gltf.scene.position.set(0, 0, 0); gltf.scene.scale.set(1, 1, 1); // 添加基础光源 const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); scene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8); directionalLight.position.set(5, 5, 5); scene.add(directionalLight); // 调整相机位置 camera.position.z = 5; // 动画循环 function animate() { requestAnimationFrame(animate); gltf.scene.rotation.y += 0.01; // 模型缓慢旋转 renderer.render(scene, camera); } animate(); }, undefined, (error) => { console.error('模型加载失败:', error); }); // 监听窗口 resize 适配尺寸 window.addEventListener('resize', () => { camera.aspect = container.clientWidth / container.clientHeight; camera.updateProjectionMatrix(); renderer.setSize(container.clientWidth, container.clientHeight); });
3. 路径验证
确保以下路径正确:
spaceship.glb与index.html/3dmodel.js在同一目录,或使用正确相对路径- 本地依赖模式下,
node_modules路径无误
完成后用Live Server启动项目,检查控制台是否有新错误,模型是否渲染到main-title区域。
内容的提问来源于stack exchange,提问作者Mora
相关产品推荐
相关产品推荐

