Global require with Browserify v2

10,202

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.

Share:
10,202
Admin
Author by

Admin

Updated on June 21, 2022

Comments

  • Admin
    Admin about 2 years

    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.