微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法在 react-three-fiber

如何解决无法在 react-three-fiber

对于用 react-three-fiber 制作的项目,我导入了以下库:

import * as THREE from 'three';
import React,{ Suspense,useState } from "react";
import { Canvas,useLoader } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";

效果很好,然后我决定为场景制作一个更整洁的 UI 并尝试根据 https://sbcode.net/threejs/dat-gui/

导入 import { GUI } from '/jsm/libs/dat.gui.module';

但是它显示一个错误

Failed to compile
./src/App.js
Module not found: You attempted to import /jsm/libs/dat.gui.module which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
This error occurred during the build time and cannot be dismissed.

这很奇怪,因为前面的四个库都在 src 之外。

然后我尝试放置相对路径,但编译器无法解析路径。

然后我尝试将 dat.gui.module.js 文件移动到 src 文件夹中,但出现了相同的无法解析错误

这是我项目的文件夹结构:

-Project
 |-node_modules
 | L-(all the ext. libs including @react-three etc.)
 |-src
 | L-App.js
 L-public
   L-index.html

如何让 dat.gui 在我的 react-three-fiber 项目中工作?

解决方法

您必须像 import { GUI } from 'three/examples/jsm/libs/dat.gui.module' 一样导入它。然后你可以像下面的例子一样在 useEffect 中使用它。

const gui = new GUI()
useEffect(() => {
  const folder = gui.addFolder("Light")
  folder.add(lightRef.current,'intensity',1,0.001)
},[])
,

您需要使用动态导入而不是静态导入将 dat.gui 导入 react.js。

而不是这个:

import { GUI } from 'three/examples/jsm/libs/dat.gui.module'

componentDidMountuseEffect 钩子中试试这个:

const { GUI } = await import('three/examples/jsm/libs/dat.gui.module')
const gui = new GUI()

或者这个:

import('three/examples/jsm/libs/dat.gui.module').then(({ GUI }) => {
  const gui = new GUI()
})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。