Best workaround for Cannot use import statement outside a module
when importing from three/jsm
#504
Replies: 1 comment 1 reply
-
Ok so I've fixed the issue by wrapping the top-level three scene component in The solution is to write your r3f components with regular imports ('ideal' scenario above), and then add them to your next app like below: import React, { useState, lazy, Suspense, useEffect } from "react";
import { styled } from "linaria/react";
import ErrorBoundary from "../../components/ErrorBoundary";
const ThreeCanvasComponent = lazy(() => import("./components/ThreeCanvasComponent"));
const App = () => {
const [hasMounted, setHasMounted] = useState(false);
useEffect(() => setHasMounted(true), []);
return (
{hasMounted && (
<ErrorBoundary fallback={null}>
<Suspense fallback={null}>
<ThreeCanvasComponent />
</Suspense>
</ErrorBoundary>
)}
<RestOfApp />
);
};
export default App; Another solution is to wrap the offending components each in import React, { Suspense, lazy } from "react";
import { Canvas } from "react-three-fiber";
import Lights from "./Lights";
const Controls = lazy(() => import("./Controls")); // has imports from three/jsm
const Model = lazy(() => import("./Planet")); // has imports from three/jsm
const ThreeCanvasComponent = () => (
<Canvas
concurrent
camera={{ position: [0, 0, 20] }}
style={{ height: "100vh", width: "100vw" }}
>
<Suspense fallback={null}>
<Lights />
<Model />
<Controls />
</Suspense>
</Canvas>
);
export default ThreeCanvasComponent; Note that neither of these solutions work if the |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm using r3f in a next.js app and running into this problem when importing
OBJLoader
, and when importingOrbitControls
fromdrei
(as that module imports fromthree/examples/jsm/
).I've seen from pmndrs/gltfjsx#20 (comment) that this is an issue with three as the files from
three/examples/jsm/
aren't written as modules, so I'm not looking for a fix.Does anyone have a workaround for this? Currently I'm doing the below, but I'm not enjoying the solution. Is there a better way?
Also, is there a reason why this is only an issue with Next and not Gatsby (which I've tried successfully before)? What is different between their Webpack setups or
react-dom-server
implementations?ideal:
workaround:
Beta Was this translation helpful? Give feedback.
All reactions