gltf文件未显示在react nextjs中

时间:2020-09-15 05:44:27

标签: reactjs three.js next.js gltf

我正在尝试使用threejs在nextjs应用程序中加载gltf文件,但是当我尝试在react项目上使用nextjs应用程序运行它时,它不起作用。这就是我使用webpack配置next.js的方式:

const withCSS = require('@zeit/next-css');
const withImages = require('next-images');

const withPlugins = require('next-compose-plugins');
module.exports = withPlugins([
    [withCSS, { cssModules: true  }],
    [withImages],
], {
    serverRuntimeConfig: {   serverRuntimeConfigValue: 'test server'  },
    publicRuntimeConfig: {   publicRuntimeConfigValue: {apiUrl:process.env.apiUrl.trim()} },
    webpack: (config, options) => {
        config.module.rules.push({
            test: /\.(glb|gltf)$/,
            use: {
                loader: 'file-loader',
            }
        })
        return config;   },exportTrailingSlash: true
});

我正在这样导入文件:

import React from 'react';
import * as THREE from 'three';
import GLTFLoader from 'three-gltf-loader';
import  TransformControls  from './TransformControls.js'
import test2 from "../../../static/images/villa.gltf";

我在componentDidmount中编写了此函数以加载gltf:

   this.loader.load(test2, gltf => {
            this.gltf = gltf.scene

            // ADD MODEL TO THE SCENE
            this.scene.add(gltf.scene);
          

         });

这是呈现gltf文件时的“网络”标签

enter image description here

1 个答案:

答案 0 :(得分:2)

为了使用file-loader正确提供资产,您必须使用_next静态目录的正确位置进行配置,如下所示:

{
  loader: 'file-loader',
  options: {
    publicPath: "/_next/static/images", // the path access the assets via url
    outputPath: "static/images/", // where to store on disk
  }
}

但是看起来您可能还需要设置以加载.bin文件并保留原始名称,因为它将在调用.load函数时被加载:

webpack: (config) => {
  config.module.rules.push({
    test: /\.(glb|gltf)$/,
    use: {
      loader: 'file-loader',
      options: {
        publicPath: "/_next/static/images",
        outputPath: "static/images/",
      }
    },
  });
  
  // For bin file
  config.module.rules.push({
    test: /\.(bin)$/,
    use: {
      loader: 'file-loader',
      options: {
        publicPath: "/_next/static/images",
        outputPath: "static/images/",
        name: '[name].[ext]' // keep the original name
      }
    },
  });
}

还将bin文件导入您的组件中:

import "../../../static/images/villa.bin";