thlorenz / browserify-shim

📩 Makes CommonJS incompatible files browserifyable.
MIT License
933 stars 87 forks source link

How do you deal with modules that expect "this" to be "window"? #171

Closed ptarjan closed 9 years ago

ptarjan commented 9 years ago

I went through all the documentation I could find, and didn't see a solution of how to use browserify-shim in this case? In my specific case, the module is https://github.com/nathanhammond/libphonenumber/blob/master/dist/libphonenumber.js#L1 where the very first statement is var aa = this, but the generic pattern is

var root = this;
root.myVariable = function() { ... };

in browserify, this is undefined. What should I do?

bendrucker commented 9 years ago

Pretty sure this is covered, see #154

ptarjan commented 9 years ago

@bendrucker Yay, you are right. PEBKAC.

If others stumble upon here, this is what worked in my package.json

  "browser": {
    "libphonenumber": "./bower_components/libphonenumber/dist/libphonenumber.js"
  },
  "browserify-shim": {
    "libphonenumber": "global:phoneUtils"
  },
ptarjan commented 9 years ago

@bendrucker what code is responsible for replacing this with window? I'm debugging an issue where my dev code has it correctly replaced, but my prod pushes still have this.

$ diff /tmp/good.js /tmp/bad.js
446c446
<     var te = window,
---
>     var te = this,
20677c20677
<                         var te = window,
---
>                         var te = this,
ptarjan commented 9 years ago

@bendrucker ok, I found the issue, babelify is putting a "use strict" into my modules, which make iife functions not automatically get window as the context. So browseify-shim is off the hook, unless you have a good idea how i can use your tool to transform my library replacing this with window?

bendrucker commented 9 years ago

https://github.com/thlorenz/browserify-shim/blob/c1c1cee6c48a3ee15044618fde078bea2d395f05/index.js#L129

There's no replacement, the wrapper is called with global