airbnb / polyglot.js

Give your JavaScript the ability to speak many languages.
http://airbnb.github.io/polyglot.js
BSD 2-Clause "Simplified" License
3.71k stars 208 forks source link

Handle no window object with Webpack #35

Closed christianalfoni closed 8 years ago

christianalfoni commented 9 years ago

In environments like Webpack there is no this to refer to the global object. But you do have global, which is the Node global object.

I suggest supporting that to ensure logging works. An other fix would be to check if root actually exists when logging.

At least now it breaks with Webpack, which is too bad :-/

ljharb commented 9 years ago

It'd be helpful to add a test to cover this case - even if it used webpack as a dev dependency.

Also, if we're making changes to the UMD, what about web workers, and node-webkit?

christianalfoni commented 9 years ago

Hm, good point... though hard to verify if it actually runs in those environments? Maybe check for known globals that has a console object? Like: (window || global), instead of (this || global). And when logging check if root actually is available, as it might not be in certain environments.

So the test case would be to run logging with an undefined root? And a defined root, but with no console object. Not sure how to verify that window and global actually exists in different environments.

ljharb commented 9 years ago

Sadly the only truly reliable way to get the global object in all environments is Function('return this')(), which breaks CSP - but if you know you're not in strict mode, you could do (function () { return this; }()) as well.

christianalfoni commented 9 years ago

Ah, interesting, yes that works with Webpack. I believe Webpack runs all modules in "strict mode" by default.

So maybe (Function('return this')()) is the best check?

ljharb commented 9 years ago

Doing that, however, utterly prevents the use of the library in Chrome apps, because CSP will error out on eval.

christianalfoni commented 9 years ago

Aha, okay, then I vote for:

(this || window || global)

Identify known environments. Webpack is becoming increasingly popular, so sad to see this lib become unusable just because of this :-)

ljharb commented 9 years ago

We'd also need self - ie, self || window || global. see https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L146-L154

christianalfoni commented 9 years ago

Cool, let me update the pull request :-)

christianalfoni commented 9 years ago

Okay, created a new commit: https://github.com/christianalfoni/polyglot.js/commit/1f5efbce5289cc79b663133c2bdfaad489851390

ljharb commented 8 years ago

(We can now use http://npmjs.com/system.global to get the global object)

ljharb commented 8 years ago

This is now obviated by #53, which removes legacy bower/component/UMD machinery.