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

Vue中使用Three.js加载OBJ文件的方法及报错解决

解决Vue项目中Three.js加载OBJ文件的模块解析错误及代码修正

一、解决模块解析失败的核心问题

报错提示Module parse failed: Unexpected token是因为Webpack没有配置处理.obj文件的加载器,需添加对应规则:

1. Vue CLI 3/4 处理方案

安装file-loader:

npm install file-loader --save-dev

在项目根目录创建或修改vue.config.js,添加文件规则:

module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.obj$/,
          use: [
            {
              loader: 'file-loader',
              options: {
                name: 'assets/objFile/[name].[hash:8].[ext]'
              }
            }
          ]
        }
      ]
    }
  }
}

Vue CLI 5+/Webpack 5 处理方案

Webpack 5自带asset/resource模块,无需额外安装loader,修改配置:

module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.obj$/,
          type: 'asset/resource',
          generator: {
            filename: 'assets/objFile/[name].[hash:8].[ext]'
          }
        }
      ]
    }
  }
}

二、修正代码中的语法与逻辑错误

你的代码存在多处语法错误和逻辑问题,修正后代码如下:

import * as THREE from 'three'
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader"
import objAddress from '../assets/objFile/testfile.obj'

export default {
  mounted() {
    console.log(this, objAddress)
    const canvas = document.querySelector('#canvas')
    const scene = new THREE.Scene()
    const renderer = new THREE.WebGL1Renderer({ canvas })
    renderer.setSize(canvas.clientWidth, canvas.clientHeight)
    
    const camera = new THREE.PerspectiveCamera(30, canvas.clientWidth / canvas.clientHeight)
    camera.position.set(0, 0, 5)
    
    const loader = new OBJLoader()
    loader.load(objAddress, (obj) => {
      scene.add(obj)
      function animate() {
        requestAnimationFrame(animate)
        renderer.render(scene, camera)
      }
      animate()
    }, (xhr) => {
      console.log((xhr.loaded / xhr.total * 100) + '% loaded')
    }, (error) => {
      console.error('OBJ模型加载失败:', error)
    })
  }
}

关键修正点:

  • 修正Three.js导入语法:import * as THREE from 'three'(原代码缺失*)
  • 修正Vuemounted钩子的语法错误(原代码括号、大括号嵌套混乱)
  • 简化OBJ文件导入路径(src目录下无需写../src)
  • 添加渲染器尺寸设置,避免画面拉伸
  • 调整相机位置,避免与模型重叠导致无法显示
  • 补充渲染循环requestAnimationFrame,确保画面持续更新
  • 修正scene.add参数错误(无需重复传入scene)
  • 增加加载进度和错误回调,便于调试

三、验证步骤

  1. 重启项目开发服务器(配置修改后需重启生效)
  2. 确保页面中存在#canvas元素且设置了宽高样式
  3. 检查OBJ文件路径正确、文件本身无损坏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:37:41