browserify / browserify-handbook

how to build modular applications with browserify

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Demystify exclude

tschaub opened this issue · comments

I'm trying to create two bundles. One with React and one that requires React. From the example in the handbook, it looks like exclude might provide what I need.

If I take the jQuery example and adapt it to use React instead of jQuery, I end up with something like this:

$ npm install react
$ browserify -r react --standalone React > react-bundle.js

then we want to just require('react') in a main.js:

console.log(require('react'));

defering to the React dist bundle so that we can write index.html:

<script src="react-bundle.js"></script>
<script src="bundle.js"></script>

and not have the React definition show up in bundle.js, then while compiling the main.js, you can --exclude react:

browserify main.js --exclude react > bundle.js

The problem with this is that when you load index.html you get an uncaught

Error: Cannot find module 'react'

Reading back through the excluding doc, I see that it suggests I might actually expect this behavior:

Another related thing we might want is to completely remove a module from the output so that require('modulename') will fail at runtime.

This completely mystified me the first time I read it. Why would someone want a require() call to fail at runtime??

The other mysterious part to me is why things work with the jQuery example but not React. In the main.js bundle from the jQuery example, the require('jquery') call is replaced with this:

(typeof window !== "undefined" ? window['jQuery'] : typeof global !== "undefined" ? global['jQuery'] : null)

I'm curious how Browserify figured out that jQuery might be assigned to the global. Is this something specific to --exclude jquery?

I'd be happy to help improve the documentation if someone could help me understand exclude.

I see now that --standalone is the source of the problems. The separate bundle works with:

browserify -r react > react-bundle.js

So it is still a mystery how require('jquery') gets replaced above. And I don't get the "so that require('modulename') will fail at runtime" bit. And I can't tell any difference in the behavior between exclude and external (though I see the implementation differs).

But I'm slightly less mystified.

It's been a few days since I'm trying to figure out what is the “official” way of getting this done but I'm still as confused as you regarding these require/exclude/external/standalone flags, and the doc doesn't help clearing it up. For now I've randomly picked exclude over external. Fingers crossed.