benbria / aliasify

Rewrite require calls in browserify modules.
MIT License
204 stars 26 forks source link

What features beyond browser field does this module add #8

Closed thlorenz closed 10 years ago

thlorenz commented 10 years ago

Hey, came across this module and am not understanding what you can do with it that the browser - replace feature cannot?

jwalton commented 10 years ago

In all honesty, it doesn't add much. I wrote this because I had a very specific use case where I needed the replacement to happen at a certain point in my transform chain.

I was writing a library which required d3. The problem with d3 is, when you require it via browserify, it effectively does:

window.d3 = blahblahblah;
module.exports = window.d3;
delete window.d3;

(Or it did when I wrote aliasify - it might have been fixed by now.) The problem with this is that, if you try to include my library on a page that already includes d3, the global d3 gets nuked by the code above, so the page can't reference d3 anymore, and obviously I don't have any control over what may or may not be happening on a page that includes my library. So, I wrote a shim which basically said:

oldD3 = window.d3;
d3 = require('d3')
window.d3 = oldD3;

(Slightly more complicated than this, but you get the idea.) So now I could replace all my require('d3')s with require('../shims/d3'). Except, I was dependent on another library which had a require('d3') in it. The problem is that debowerify would pick up the require('d3') and replace it with a reference to the bower d3 lib before we got to the "browser" replace step, so I needed a way to rewrite this third party library's require('d3') call before debowerify had a chance to touch the file.

Now that I know a lot more about browserify, I suspect a better solution would be to do away with debowerify and just use the browser replace. Or even rewrite debowerify as a opts.resolve() handler to pass to browserify, which would probably make it happen after the browser replacement step.

A smart person would also point out that I could have just submitted a pull request to d3 to fix this behavior. :P

But, I've written this now, so I put it here on the Internet in the hopes that someone else will find it useful. :)

thlorenz commented 10 years ago

Ah, makes sense.