GoogleChromeLabs / worker-plugin

👩‍🏭 Adds native Web Worker bundling support to Webpack.
https://npm.im/worker-plugin
Apache License 2.0
1.91k stars 79 forks source link

Warning (workerize-loader): output.globalObject is set to "window". It should be set to "self" or "this" to support HMR in Workers #20

Closed filipesilva closed 5 years ago

filipesilva commented 5 years ago

Heya,

I'm trying to follow up your initial work in https://github.com/angular/angular-cli/pull/12575.

I see Warning (workerize-loader): output.globalObject is set to "window". It should be set to "self" or "this" to support HMR in Workers when serving, but not when building.

That warning seems to come from here: https://github.com/GoogleChromeLabs/worker-plugin/blob/cb00d315157412c405f9441bd7ff7662e6c16eb9/src/loader.js#L33

What's the intended way of addressing this warning? I'd like to keep the globalObject settings of the main compilation unaltered.

As a side-note, the name workerize-loader is misleading. It took me a while to figure out that it came from this package since I was looking for a workerize-loader in node modules.

developit commented 5 years ago

Hi @filipesilva! I've corrected the plugin name in those warnings, good catch!

The best way to address this warning is to always set output.globalObject to a universal value, so that builds are agnostic to their runtime environment. Webpack will at some point create a universal output mode (Browser + Modules + Node + Workers) that does this, but until then this is required:

output: {
  globalObject: "(typeof self!='undefined'?self:global)"
  // or, if not targeting native JS Modules in Node:
  globalObject: "(typeof self!='undefined'?self:this)"
}

This allows hot updates to use self in all browser contexts (web, workers & worklets), and this or global in Node.

See webpack/webpack#6642 and webpack/webpack#6525 for extensive context.

FWIW, despite the warning, worker-plugin actually does set globalObject for the child compiler it creates: https://github.com/GoogleChromeLabs/worker-plugin/blob/6a903d5b862667f6d906a5527df676b6e933c23c/src/loader.js#L41

For now, I've added a new globalObject configuration option to the plugin. Setting it to false will disable this warning.

filipesilva commented 5 years ago

There's something I don't quite understand though. If the child compiler already uses the right globalObject, why does it matter what globalObject the parent uses?

developit commented 5 years ago

Released as 3.1.0

developit commented 5 years ago

@filipesilva TBH that part I wish I could get more clarity on. I don't think it's enough only to set the correct value for the child compiler, perhaps because other chunks can be loaded into that context from other compilers.

filipesilva commented 5 years ago

Hm yes, that would make sense. Regardless, thank you for the swift reply, will update 👍