webpack - 无法在 React 应用程序中使用 GLTFLoader 从本地目录加载 GLTF 文件。它从外部 URL 正确加载

标签 webpack three.js

编辑:在 webpack.config.js 中用“url-loader”替换“gltf-webpack-loader”似乎可以解决问题。

我正在尝试使用 Three.js 在 React 应用程序中渲染 3d 模型,但是我是

从本地目录加载 GLTF 文件时出现问题。当我尝试使用 GLTF Loader 加载 GLTF 文件时,出现 404(未找到)错误。它确实有效 当我从外部 URL 加载 GLTF 文件时正确。

GLTF 文件本身可以工作。我在一个单独的非 react 项目(只是一个 html 文件)中测试了它,其中 GLTF 文件使用 GLTFLoader 加载并由本地服务器提供服务。

在单独的非 react 项目中,THREE.js 和 GLTFLoader 加载自

  <script src="https://unpkg.com/three@0.102.0/build/three.min.js"></script>
  <script src="https://unpkg.com/three@0.102.0/examples/js/loaders/GLTFLoader.js"></script>

而在 React 项目中,它们是从 npm 模块加载的:“three”和“three-gltf-loader”。

下面是我项目中与加载 GLTF 文件相关的代码。

import * as THREE from 'three';
import GLTFLoader from 'three-gltf-loader';
import Car from './models/Low-Poly-Racing-Car.gltf';

...

loader.load(
    Car,
    (gltf) => {
        this.customLayer.scene.add(gltf.scene);
    }, null, (err) => {
        console.log(err);
    }
);

...

同样,这会导致本地文件出现 404 错误,但外部链接如 https://docs.mapbox.com/mapbox-gl-js/assets/34M_17/34M_17.gltf工作得很好。

这是 webpack 版本 1.15.0。我已经尝试过修改和不修改 webpack.config.json。我尝试对 webpack.config.json 的修改是添加

      {
        test: /\.(gltf)$/,
        loader: "gltf-webpack-loader"
      },
      {
        test: /\.(bin)$/,
        loader: 'file-loader'
      }

加载器数组。这允许

import Car from './models/Low-Poly-Racing-Car.gltf';

工作。

对于 GLTFLoader 的路径参数,我尝试使用上面看到的名为 Car 的变量,以及包含我尝试过的不同目录的相对路径的字符串:

"../../../images/models/Low-Poly-Racing-Car.gltf"
"./models/Low-Poly-Racing-Car.gltf"
"../../../public/models/Low-Poly-Racing-Car.gltf"
"../../../public/models/Low-Poly-Racing-Car.gltf"

当我从上述目录导入名为 Car 的变量时,我得到值:

"/in-memorye5d217e7245bef6f258a6f535019c43e.gltf"

非常感谢任何有关将 GLTF 文件本地加载到此 React 项目的帮助!

最佳答案

If you load models or textures from external files, due to browsers' same origin policy security restrictions, loading from a file system will fail with a security exception.

查看文档:
https://threejs.org/docs/#manual/en/introduction/How-to-run-things-locally

关于webpack - 无法在 React 应用程序中使用 GLTFLoader 从本地目录加载 GLTF 文件。它从外部 URL 正确加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55940928/

相关文章:

javascript - Dropzone 未定义,在 symfony 上使用 webpack

three.js - THREE.PerspectiveCamera 90 度视野无失真

javascript - Three.js Collada - 在 Three js 中加载多个 Collada 对象

three.js - 纹理的类型和格式之间有什么关系

typescript - 将 globalize 与 webpack 2 和 typescript 结合使用

javascript - 使用 webpack 和 babel 的动态 import() 语法错误

javascript - 如何让简洁的 webpack 插件正常工作

javascript - 如何为多个环境设置环境变量?

three.js - 我是三个js新手,如何创建一个天空穹顶

javascript - React : Using document. QuerySelector 作为库的一部分