[英]Why does my D3 code break when I set the script type to module?
I am working on a project built with Javascrpt, jQuery, and Vite.js.我正在开发一个使用 Javascrpt、jQuery 和 Vite.js 构建的项目。 My colleague built a data visualization using D3 - a US states map - that I need to implement in the project on a specific page.
我的同事使用 D3(美国各州地图)构建了数据可视化,我需要在项目中的特定页面上实现该可视化。 They built the component using test data, my job is basically to load the component onto a page passing it actual returned data from an API call.
他们使用测试数据构建了组件,我的工作基本上是将组件加载到一个页面上,并将其从 API 调用返回的实际数据传递给它。
Everything in the test project works perfectly, but when I tried to implement this code into a script file in the project - literally copying and pasting from the working version - I got an error saying certain properties could not be read.测试项目中的所有内容都运行良好,但是当我尝试将此代码实现到项目中的脚本文件中时——实际上是从工作版本中复制和粘贴——我收到一条错误消息,指出无法读取某些属性。 After failing to debug for sometime, I randomly tried removing
type="module"
from the script tag link in HTML, and boom, everything worked.在调试了一段时间后,我随机尝试从 HTML 中的脚本标记链接中删除
type="module"
,然后,一切正常。 Does anyone have an idea of why this would be?有谁知道为什么会这样? I cannot get this code to run when the script type is set to module, except I need the script type to be set to module since I'm importing lots of components for other aspects of the page.
当脚本类型设置为模块时,我无法运行此代码,除非我需要将脚本类型设置为模块,因为我正在为页面的其他方面导入大量组件。
With the way the CodePen is set up, I couldn't replicate the issue since the HTML and JS files are automatically linked.使用 CodePen 的设置方式,我无法复制该问题,因为 HTML 和 JS 文件是自动链接的。 But if you copy this code into your editor, and then in the html, set the the JS file to a module ` You'll see the issue.
但是如果你把这段代码复制到你的编辑器中,然后在 html 中,将 JS 文件设置为一个模块`你会看到问题。
Thanks.谢谢。 I'm at a total loss for what to do here.
我完全不知道在这里做什么。 I could put all the D3 code in it's own script file, but then I have no way pass it variables from other files if it's not a module.
我可以将所有 D3 代码放在它自己的脚本文件中,但是如果它不是模块,我就无法从其他文件中传递变量。
Per the comments, the following lines in my original code were not working in strict mode:根据评论,我原始代码中的以下几行在严格模式下不起作用:
this.uStates = uStates;
this.uStatePaths = uStatePaths;
The fix was simple, I just needed to write the following instead:修复很简单,我只需要编写以下代码:
window.uStates = uStates;
window.uStatePaths = uStatePaths;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.