NextJS搭配@react-three/drei遇TypeError:URL解析失败求助
NextJS + @react-three/drei useGLTF URL解析错误问题
我正在使用@react-three/drei开发带有3D动画的NextJS应用,项目根目录的/public/desktop_pc/文件夹下存放着scene.gltf文件,调用useGLTF钩子导入该文件时,出现如下错误:
TypeError: Failed to parse URL from /desktop_pc/scene.gltf
组件代码如下:
import { useGLTF } from "@react-three/drei"; import React from "react"; const Computers = () => { const computer = useGLTF("/desktop_pc/scene.gltf"); return <div>Computers</div>; }; export default Computers;
已尝试以下方案但未解决问题:
- 动态导入
- 懒加载导入
- 安装Three与three-stdlib npm包
- 指定组件到文件的精确路径
- 在路径开头添加点(
./desktop_pc/scene.gltf)
解决方法
方案1:静态导入资源+适配SSR路径解析
在NextJS中直接静态导入GLTF资源,再将资源路径传入useGLTF,避免服务端渲染时的路径解析异常:
import { useGLTF } from "@react-three/drei"; import React from "react"; // 直接导入public目录下的模型文件 import computerModel from "/public/desktop_pc/scene.gltf"; const Computers = () => { const computer = useGLTF(computerModel.src); // 渲染模型场景 return <primitive object={computer.scene} />; }; export default Computers;
方案2: useEffect配合预加载规避SSR问题
利用客户端渲染时的环境加载模型,避免服务端路径解析错误:
import { useGLTF } from "@react-three/drei"; import React, { useEffect, useState } from "react"; const Computers = () => { const [model, setModel] = useState(null); useEffect(() => { const loadModel = async () => { // 预加载模型文件 const loadedModel = await useGLTF.preload("/desktop_pc/scene.gltf"); setModel(loadedModel); }; loadModel(); }, []); return model ? <primitive object={model.scene} /> : <div>Loading...</div>; }; export default Computers;
方案3:升级依赖并配置Webpack规则
- 确保依赖版本兼容,升级到稳定版:
npm update next @react-three/drei three
- 在
next.config.js中添加GLTF文件的Webpack加载规则(需先安装file-loader:npm install file-loader --save-dev):
/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { config.module.rules.push({ test: /\.(gltf|glb)$/, use: [ { loader: 'file-loader', options: { outputPath: 'static/desktop_pc/', publicPath: '/_next/static/desktop_pc/', }, }, ], }); return config; }, }; module.exports = nextConfig;
内容的提问来源于stack exchange,提问作者Itay Tur
相关产品推荐
相关产品推荐

