material-svelte / vite-web-test-runner-plugin

MIT License
39 stars 13 forks source link

Assign to window.global, not just global #9

Closed IanVS closed 3 years ago

IanVS commented 3 years ago

Otherwise errors are thrown like ReferenceError: Can't find variable: global

betaboon commented 3 years ago

this is weird. assigning global should be enough oO

https://developer.mozilla.org/en-US/docs/Web/API/Window/window

global variables of your script are in fact properties of window:

var global = {data: 0};
alert(global === window.global); // displays "true"
IanVS commented 3 years ago

I'm not sure, maybe it has something to do with the way that web-test-runner works? All I know is that global = window; blows up, and window.global = window works fine. ¯\(ツ)

betaboon commented 3 years ago

would you be able to provide a repro for that case?

IanVS commented 3 years ago

Sure, I added it to https://github.com/IanVS/vite-wtr-issue-8/tree/window-global, the branch is window-global. If you check that out, npm install, then npm test, you should see the error.

betaboon commented 3 years ago

@IanVS in your repro you are defining the global = window; within a <script type="module"> block. as the examples should you need to defined it in a <script> block.

doing so makes your repro work on my end

IanVS commented 3 years ago

Oh interesting. Can you explain why that makes a difference? And anyway, is it not better to use a module whenever possible?

It still seems like maybe this PR is safer, and might avoid others having the same confusion.

betaboon commented 3 years ago

i think in this case it is better to not use a module. as i understand it the relevant aspect of the difference is this:

- Modules are only executed once, even if they have been referenced in multiple <script> tags.
- Last but not least, let's make this clear — module features are imported into the scope of a single script — they aren't available in the global scope. Therefore, you will only be able to access imported features in the script they are imported into

source

IanVS commented 3 years ago

OK, although I think that's talking about imports. I'm perfectly able to assign to the window from a module, as shown in my branch.

At any rate, is there a downside to this PR? It isn't changing the script over to a module, it just is more explicit that global is being added to the window, which is what is happening no matter what.

betaboon commented 3 years ago

it just is more explicit that global is being added to the window, which is what is happening no matter what.

this is a valid point.

if you could adapt type=module in all the examples and prefix all the variables (global and process) with window. to make it consistent all across i would be very much willing to merge :)

IanVS commented 3 years ago

LMK if this is what you had in mind, thanks.

betaboon commented 3 years ago

perfect. could you just cleanup the history (make it one commit) ? :)