1

Problem:

Let's say I want to create a React App with a 3D component on the left and some other UI components on the right.

The 3D stuff is done with three.js and let's say I want to clone this 3D app: https://threejs.org/examples/?q=edit#webgl_geometry_spline_editor

Currently I am globally including the scripts in my index.html that are needed for the 3D app like this:

<script src="../build/three.js"></script>
<script src="js/controls/DragControls.js"></script>
<script src="js/controls/OrbitControls.js"></script>
<script src="js/controls/TransformControls.js"></script>
<script src="js/libs/stats.min.js"></script>
<script src="js/libs/dat.gui.min.js"></script>

(Leaving out %PUBLIC_URL% for brevity).

Now in my React 3DComponent I can use the objects and methods in these scripts by using the global window object, like this:

controls = new window.THREE.OrbitControls(camera, renderer.domElement);
var clock = new window.THREE.Clock();

Questions:

  1. Is there a more elegant way for importing these scripts so I don't have to import the scripts to the global space? I could import three.js as a module, but some of the other scripts (DragControls, OrbitControls) require the objects in the main Three.js file so I have to keep it in global space.

  2. Is there any way to shorten these calls by leaving out the call to the global window object? Without this I could copy and paste the sample codes for the 3d scenes without having to call ".window." before every method and object calls.

Sorry if these questions are somewhat nooby but I'm new to React and Three.js.

ivan
  • 111
  • 1
  • 7

1 Answers1

0

Create three.js file and paste the below code.

const THREE = require("three");
global.THREE = THREE;
if (!window.addEventListener) window.addEventListener = () => {};
require("three/examples/js/controls/DragControls.js");
require("three/examples/js/controls/OrbitControls.js");
require("three/examples/js/controls/TransformControls.js");
require("three/examples/js/libs/stats.min.js");
require("three/examples/js/libs/dat.gui.min.js");
export default THREE;

Import this file into any of your component.

import THREE from "./three";

Hope this helps.

satheesh
  • 403
  • 5
  • 15