Global require with Browserify v2
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.
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Admin
Updated on June 21, 2022Comments
-
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 norequire
function defined on the page.It appears that the
require
function defined by browserify inbundle.js
is inside of an IIFE, so I can't use that. Is it possible to throw this one out in place of a globalrequire
?<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.