简体   繁体   中英

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. My colleague built a data visualization using D3 - a US states map - that I need to implement in the project on a specific page. 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.

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. 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. 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.

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM