Global require with Browserify v2

user1082754 picture user1082754 · Mar 17, 2013 · Viewed 10.2k times · Source

I want to use Browserify to bundle my files, but I then need to require one of the modules inside of my Browserify bundled bundle.js on the HTML page itself. This is currently not possible because there is no require function defined on the page.

It appears that the require function defined by browserify in bundle.js is inside of an IIFE, so I can't use that. Is it possible to throw this one out in place of a global require?

<script src="bundle.js"></script>
<script>
  // Require the `app` module inside of `bundle.js`
  var app = require('app');
  app.start();
</script>

I need to do this because my app.start function requires some JSON is passed to it which can only be rendered by the server-side template.

N.B. I am using Browserify v2.

Answer

substack picture substack · Mar 17, 2013

You can use -r to expose a global require() function for the files you specify:

x.js:

module.exports = function (n) { return n * 111 }

Console

$ browserify -r ./x.js > bundle.js

then in your html:

<script src="bundle.js"></script>
<script>
    var x = require('./x.js');
    console.log(x(3))
</script>

will print 333.

In your case, just do browserify -r app to expose require('app') to the external context.