SigmaJS v2在HTML文档加载模块失败 求正确实现方案
SigmaJS v2 加载运行问题解决方案
错误原因
- 你安装的npm版sigma v2是面向现代前端构建工具的源码包,不能直接用requireJS加载未打包的源文件
- 项目页面放在
node_modules目录下属于错误操作,项目业务文件需要和node_modules目录平级存放 - sigma v2的API和v1版本不兼容,你使用的
new sigma()+s.graph.read()是v1的写法,v2已经不支持
最简可行方案(无需构建工具、无需requireJS)
自行下载graphology和sigma的UMD格式打包文件到本地,跳过npm安装和模块加载器配置,修改后的完整代码如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Sigma Demo</title> <style> html, body { height: 100%; margin: 0; } #sigma-container { width: 100%; height: 100%; } </style> <!-- 引入本地存放的graphology和sigma UMD包 --> <script src="./graphology.umd.min.js"></script> <script src="./sigma.min.js"></script> </head> <body> <div id="sigma-container"></div> <script> // 初始化graph实例 const graph = new graphology.Graph(); // 导入你的节点和边数据 const data = { nodes: [ { id: "n0", label: "node 1", x: 0, y: 0, size: 3, color: '#00BCD4' }, { id: "n1", label: "node 2", x: 3, y: 1, size: 2, color: '#00BCD4' }, { id: "n2", label: "node 3", x: 1, y: 3, size: 1, color: '#00BCD4' }, { id: "n3", label: "node 4", x: 6, y: 0, size: 3, color: '#00BCD4' }, { id: "n4", label: "node 5", x: 5, y: 1, size: 2, color: '#00BCD4' }, { id: "n5", label: "node 6", x: 4, y: 3, size: 1, color: '#00BCD4' } ], edges: [ { id: "e0", source: "n0", target: "n1", color: '#545454', type:'line'}, { id: "e1", source: "n1", target: "n2", color: '#545454', type:'line'}, { id: "e2", source: "n1", target: "n3", color: '#545454', type:'line'}, { id: "e3", source: "n1", target: "n4", color: '#545454', type:'line'}, { id: "e4", source: "n2", target: "n0", color: '#545454', type:'line'}, { id: "e5", source: "n2", target: "n3", color: '#545454', type:'line'}, { id: "e6", source: "n3", target: "n2", color: '#545454', type:'line'}, { id: "e7", source: "n4", target: "n5", color: '#545454', type:'line'}, { id: "e8", source: "n4", target: "n3", color: '#545454', type:'line'}, { id: "e9", source: "n5", target: "n0", color: '#545454', type:'line'} ] }; graph.import(data); // 初始化sigma实例 const renderer = new Sigma(graph, document.getElementById("sigma-container"), { labelColor: 'node', minEdgeSize: 0.1, maxEdgeSize: 2, minNodeSize: 5, maxNodeSize: 5 }); </script> </body> </html>
直接在本地打开该html文件即可正常运行。
如需使用npm包配合构建工具的操作步骤
- 在项目根目录(和node_modules平级)执行
npm install vite -D安装轻量化构建工具 - 根目录新建index.html,引入入口js文件:
<script type="module" src="./index.js"></script> - 根目录新建index.js,写入sigma初始化逻辑(用ESM语法导入graphology和sigma即可)
- 在package.json的scripts字段添加命令:
"dev": "vite" - 执行
npm run dev启动本地服务后访问即可
内容的提问来源于stack exchange,提问作者xxestter
相关产品推荐
相关产品推荐

