You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ForceGraph2D遇导入错误:无法从非ES模块导入'drag'命名导出

解决ForceGraph2D导入'drag'时的模块导出错误
  • 确认导入来源:drag并非force-graph的导出项,它属于d3-drag库。先安装依赖:

    npm install d3-drag
    

    再正确导入:

    import { drag } from 'd3-drag';
    
  • 使用force-graph内置拖拽能力:force-graph本身提供开箱即用的拖拽配置,无需单独导入drag。示例代码:

    import ForceGraph from 'force-graph';
    
    const graph = ForceGraph()
      (document.getElementById('graph-container'))
      .enableDrag(true) // 开启节点拖拽
      .nodeDragListener((node, event) => {
        // 自定义拖拽触发逻辑
      });
    
  • 调整模块环境配置:确保项目package.json中声明ES模块类型,避免解析错误:

    {
      "type": "module"
    }
    

    若使用CommonJS环境,改用require导入:

    const ForceGraph = require('force-graph');
    const { drag } = require('d3-drag');
    
  • 适配force-graph版本:版本不兼容可能导致导出结构变化,尝试升级或降级到稳定版本:

    # 升级到最新版
    npm update force-graph
    # 或降级到指定稳定版(示例)
    npm install force-graph@1.44.0
    

内容的提问来源于stack exchange,提问作者Dama Ramesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 16:43:11