在 Next.js 应用中加载 gltf 场景时,有两种解决方法可供选择。第一种方法是使用绝对路径加载 gltf 文件,这可以避免路径错误,导致无法加载场景。具体代码如下:
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { getAbsoluteURL } from '../utils/helpers' // 自定义方法,将相对路径转换为绝对路径
const gltfLoader = new GLTFLoader()
const gltfURL = getAbsoluteURL('/models/your_scene.gltf') // 传递 gltf 文件相对路径
gltfLoader.load(gltfURL, (gltf) => {
// 场景加载后的回调函数
})
第二种方法是通过 nextjs 配置文件(next.config.js)设置 public 文件夹作为静态资源路径。具体代码如下:
// next.config.js
module.exports = {
// 设置 public 文件夹作为静态资源路径
// 访问 public 文件夹下的文件时,无需添加前缀 '/public/'
// 例如,public 文件夹下的 your_scene.gltf 文件,访问路径为 '/your_scene.gltf'
// 即可在页面中加载场景文件
webpack: (config) => {
config.module.rules.push({
test: /\.(glb|gltf)$/,
use: {
loader: 'file-loader',
options: { publicPath: '/_next/static/', outputPath: 'static/' }
}
})
return config
}
}
以上两种方法都可以解决部署 Next.js 应用无法加载 gltf 场景的问题。