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

在React+Three.js(Vite环境)中加载.obj模型遇语法错误

解决Vite+React中导入.obj模型的语法错误问题

问题根源

直接导入.obj文件时,Vite会默认把它当作JavaScript模块解析,但.obj是3D模型格式,语法不符合JS规范,所以触发第一行的语法错误。

解决方法

方法一:配置Vite识别.obj为静态资源(多模型场景推荐)

在项目根目录的vite.config.js中添加资源类型配置,让Vite把.obj文件当成静态资源处理,导入时直接拿到文件URL:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  assetsInclude: ['**/*.obj'] // 新增此行,识别所有.obj文件
})

方法二:使用import后缀(单模型场景快速解决)

不用修改配置,直接在导入语句后加?url,强制Vite只返回文件URL,不解析文件内容:

import frame from './assets/230x50.obj?url'

额外修复:THREE未导入的问题

你的ModelViewer组件中使用了THREE.Box3和THREE.Vector3,但没有导入Three.js,会导致运行时错误,需要在组件顶部添加:

import * as THREE from 'three'

修正后的ModelViewer组件代码

import React, { useMemo } from 'react';
import { Canvas, useLoader } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader';
import * as THREE from 'three'; // 新增THREE导入

const ModelViewer = ({ objModel }) => {
  const obj = useLoader(OBJLoader, objModel);

  const center = useMemo(() => {
    if (!obj) return [0, 0, 0];
    const box = new THREE.Box3().setFromObject(obj);
    const centerVector = box.getCenter(new THREE.Vector3());
    return centerVector.toArray();
  }, [obj]);

  return (
    <div style={{ height: '100%', width: '100%' }}>
      <Canvas style={{ height: '100%', width: '100%' }}>
        <ambientLight intensity={0.5} />
        <pointLight position={[10, 10, 10]} />
        {obj && <primitive object={obj} position={center} />}
        <OrbitControls/>
      </Canvas>
    </div>
  );
};

export default ModelViewer;

内容的提问来源于stack exchange,提问作者Etch-a-sketch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 19:15:13