Resolving “Error [ERR_REQUIRE_ESM]: require() of ES Module” in NextJS
In my BlitzJS project (which in turn utilizes NextJS), I ran into this error:
Error: require() of ES Module /home/me/project/node_modules/three/examples/jsm/controls/DragControls.js from /home/me/project/node_modules/3d-force-graph/dist/3d-force-graph.common.js not supported. Instead change the require of DragControls.js in /home/me/project/node_modules/3d-force-graph/dist/3d-force-graph.common.js to a dynamic import() which is available in all CommonJS modules.
The code causing the error was this:
import ForceGraph from "force-graph"
const MyComponent = () => {
const myGraph = ForceGraph()
}
A quick refactor (for refernece including some additional code) resolved the issue:
// File: Graph.ts
import ForceGraph from "force-graph"
import data from "./data"
export default function Graph() {
const myGraph = ForceGraph()
const node = document.getElementById("myIdTag")
if (node != null) myGraph(node).graphData(data)
return null
}
// File: MyComponent.tsx
import dynamic from "next/dynamic"
const Graph = dynamic(
() => {
return import("./Graph")
},
{ ssr: false }
)
const MyComponent = () => {
return (
<div>
<Graph />
</div>
)
}
export default MyComponent