新手求助:分离HTML与JS代码并引入第三方库的实现方法
问题分析与解决方案
你的代码分离后无法运行,核心问题有两个:
- 你在
index2.js里用了ES模块的import语法,但HTML里引用脚本时没声明type="module",浏览器会把它当作普通脚本处理,无法识别import - 同时引入了Three.js的全局版本和模块版本,两者会产生冲突
修正步骤:
- 修改HTML的脚本引用
把引用index2.js的脚本标签加上type="module",让浏览器按ES模块规则解析它:
<script type="module" src="./index2.js"></script>
- 移除重复的Three.js全局引入
3d-force-graph本身依赖Three.js,且你用了模块版本的UnrealBloomPass,直接保留importmap即可,删掉全局的Three.js脚本:
<!-- 删掉这行重复引入 --> <script src="https://unpkg.com/three@0.150.1/build/three.js"></script>
- 简化JS代码
模块脚本默认会在DOM加载完成后执行,不需要window.onload包裹,直接编写逻辑即可。
修正后的完整代码:
index2.html
<!DOCTYPE html> <html> <head> <style> body { margin: 0; } </style> <script src="https://unpkg.com/3d-force-graph@1.71.2/dist/3d-force-graph.js"></script> </head> <body> <div id="3d-graph"></div> <script type="importmap"> { "imports": { "three": "https://unpkg.com/three@0.150.1/build/three.module.js" }} </script> <script type="module" src="./index2.js"></script> </body> </html>
index2.js
import { UnrealBloomPass } from 'https://unpkg.com/three@0.150.1/examples/jsm/postprocessing/UnrealBloomPass.js'; const gData = { nodes: [ { id: "node1", name: "Node 1" }, { id: "node2", name: "Node 2" }, { id: "node3", name: "Node 3" }, ], links: [ { id: "link1", name: "link 1", source: "node1", target: "node2" }, { id: "link2", name: "link 2", source: "node2", target: "node3" }, { id: "link3", name: "link 3", source: "node3", target: "node1" }, ] } const Graph = ForceGraph3D() (document.getElementById('3d-graph')) .graphData(gData) const bloomPass = new UnrealBloomPass(); bloomPass.strength = 3; bloomPass.radius = 1; bloomPass.threshold = 0.1; Graph.postProcessingComposer().addPass(bloomPass);
额外提示
- 用模块脚本时,本地测试最好用本地服务器(比如
npx serve),避免直接打开HTML文件引发的跨域问题 - 后续扩展时,可以把数据、图形配置等拆分成单独的模块文件,进一步提升代码可维护性
内容的提问来源于stack exchange,提问作者furynerd
相关产品推荐
相关产品推荐

