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

使用Three.js加载GLTF模型时遭遇Uncaught SyntaxError错误的求助

Three.js加载GLTF模型时遭遇Uncaught SyntaxError错误的求助

我正在用Three.js做一个简单的小游戏,第一步是加载GLTF模型,但遇到了这个错误:

Uncaught SyntaxError: Unexpected token ‘:’ (at abarth131.gltf?import:2:9)

我已经尝试过这些方法:

  • 检查文件路径
  • 将GLTF文件移到public目录下
  • 在GLTF查看器里模型能正常加载

我实在不知道问题出在哪了,这是我的代码:

let scene, camera, renderer, light

function init(){
  scene = new three.Scene()
  scene.background = new three.Color(0xdddddd)

  camera = new three.PerspectiveCamera(40, window.innerWidth/window.innerHeight,1 ,5000)
  light = new three.AmbientLight(0x404040, 100)
  scene.add(light)

  renderer = new three.WebGLRenderer({antialias:true})
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  let loader = new GLTFLoader()
  loader.load('../public/abarth131/abarth131.gltf', (gltf) => {
    scene.add(gltf.scene)
    renderer.render(scene,camera)
  })
}
init()

我用的是Vite开发,纯JS环境(抱歉我的英语有点奇怪,我讲西班牙语)。任何帮助我都感激不尽!

附Chrome开发者工具里的错误截图:
Chrome控制台错误截图


嘿,我来帮你分析下这个问题!这个错误的核心原因是Vite的资源路径处理逻辑导致浏览器把GLTF文件当成JavaScript模块解析了,GLTF本质是JSON格式,开头的冒号不符合JS语法,所以才会抛出语法错误。

给你几个针对性的解决步骤:

1. 修正模型加载路径(最关键)

Vite中public目录下的资源会被直接部署到项目根目录,所以访问这些资源必须用绝对路径,而不是你代码里的相对路径../public。把加载代码改成这样:

loader.load('/abarth131/abarth131.gltf', (gltf) => {
  scene.add(gltf.scene)
  renderer.render(scene,camera)
})

注意路径开头的斜杠/,它代表项目根目录,会自动对应到你本地的public文件夹。

2. 确认Three.js的导入方式正确

我看到你代码里直接用了three.Scene,但在Vite环境下,你需要先正确导入Three.js和GLTFLoader:

// 在代码最顶部添加导入语句
import * as THREE from 'three'
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'

然后把代码里的three替换成THREE(比如new THREE.Scene()),否则可能会出现全局变量未定义的问题。

3. 添加错误回调排查细节

给GLTFLoader加上错误回调,能帮你更精准定位问题:

loader.load('/abarth131/abarth131.gltf', 
  (gltf) => {
    scene.add(gltf.scene)
    renderer.render(scene,camera)
  },
  (progress) => {
    console.log(`加载进度:${Math.round((progress.loaded/progress.total)*100)}%`)
  },
  (error) => {
    console.error('模型加载失败:', error)
  }
)

4. 检查模型文件完整性

虽然你说在GLTF查看器里能正常加载,但要确认public/abarth131目录下的所有相关文件(比如.bin纹理文件、贴图等)都完整,没有遗漏或损坏。

按照这些步骤修改后,应该就能顺利加载模型了!如果还有问题可以再补充细节~

备注:内容来源于stack exchange,提问作者Jesús Fernández

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 08:58:05