无法在反应三光纤中导入 dat.gui



对于使用 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 之外。

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

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

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

-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', 0, 1, 0.001)
}, [])

你需要使用 Dynamic import 而不是 static import 将 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()
})

dat.gui库中导入GUI

import * as dat from "dat.gui";

或者只是使用dat-gui-react

反应哒哒。图形用户界面

最新更新