vasturiano / force-graph

Force-directed graph rendered on HTML5 canvas
https://vasturiano.github.io/force-graph/example/directional-links-particles/
MIT License
1.59k stars 249 forks source link

ForceGraph is not a Function #252

Open henriqueutsch opened 2 years ago

henriqueutsch commented 2 years ago

I'm try load ForceGraph on my component but appear this error: ForceGraph is not a function

or when I try with import method this error appear.

Must use import to load ES Module: /front/node_modules/d3-selection/src/index.js require() of ES modules is not supported. require() of /front/node_modules/d3-selection/src/index.js from /front/node_modules/force-graph/dist/force-graph.common.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /front/node_modules/d3-selection/package.json.

This is my source code component. https://gist.github.com/henriqueutsch/9122db474194cda741457d8934b9e327

vasturiano commented 2 years ago

@henriqueutsch sounds like you're having trouble requiring d3-selection into your app. Which makes sense because that particular module doesn't support CommonJS exports any longer. Any reason why you can't use ES modules (import syntax) in your app instead?

oneillsp96 commented 2 years ago

I'm seeing a similar error when trying to run a test with Vitest, which is based on ES Modules:

Error: require() of ES Module C:\Users\pathtoprojecthere\node_modules\d3-selection\src\index.js 
from
 C:\Users\pathtoprojecthere\node_modules\force-graph\dist\force-graph.common.js not supported.

Instead change the require of index.js in C:\pathtoprojecthere\node_modules\force-graph\dist\force-graph.common.js to a dynamic import() which is available in all CommonJS modules.

However I don't see a dist folder in force-graph....very confused. The version I'm using is "react-force-graph-2d": "1.23.10",

oneillsp96 commented 2 years ago

Ah...I see the rollup config is creating both a commonjs export and a ES modules export....is there a way to control which one I get? This is how I'm importing: import ForceGraph2D from "react-force-graph-2d";

vasturiano commented 2 years ago

The package.json defines commonJs and ES modules entry points to tell your app where to find its intended bundle: https://github.com/vasturiano/force-graph/blob/fcb2647526be264b48098d38b446f34377d6e264/package.json#L6-L7

So it all depends on your app build system. If you find that you end up with the commonJs version, it's because your app build is looking for that.