无法在 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()
})