require is not defined error with browserify require is not defined error with browserify node.js node.js

require is not defined error with browserify


The "require" function is only available in the "bundle.js" script context. Browserify will take all the script files necessary and put them into the "bundle.js" file, so you should only have to include "bundle.js" in the HTML file, not the "script.js" file.


I personally prefer to keep my library code and application code seperate. So i also create something like a bundle.js and a script.js.

there is a simple workaround, that makes this work. This is somewhere in my browserify-file:

window.require = require;

this will expose require into the "global" namespace. You can then require all you want from your script.js.

You do give up ONE advantage, though: you'll have to include all the required libraries in your browserify file. You don't get the luxury of it finding all your dependencies, then!

I fully expect people to cry "dirty hack" or "this is not how it's meant to be". Yes, maybe. But I want those files seperate. And as long as i don't include anything else that is called "require", i'll be fine, thank you very much.

Sometimes one global can make all the difference.


It seems that to run a script like that you have to use standalone on the bundle.

browserify main.js --standalone Bundle > bundle.js

After that you should have window.Bundle in bundle.js.
So at that point you should be able to access from script.js.

if you are using grunt

If you are using grunt install grunt-browserify.

npm install grunt-browserify --save-dev

And then on grunt.js Gruntfile:

// Add the taskgrunt.loadNpmTasks('grunt-browserify');// Add the configuration:browserify: {    dist: {        options: {            // uncomment if you use babel            // transform: [            //     ["babelify", { "presets": ["env"] }]            // ],            browserifyOptions: {                standalone: 'Bundle'            }        },        files: {           "bundle.js": ["main.js"]        }    }},

if you are using gulp

 // on your build task var bundled = browserify('main.js', { standalone: 'Bundle' })               .bundle()               .pipe(source('bundle.js'))               .pipe(gulp.dest(outDir));

See here for Chart.js gulp file.

if you are using babel

If you are using babel and es6 probably you are exporting your Bundle class.

// you should have something like that class Bundle {    ...}export default Bundle;

So because of babel now to use Bundle you should use Bundle.default and so:

// in script.jsvar bundle = new Bundle.default();

To avoid this syntax you can override Bundle with Bundle.default.

At the end of bundle.js insert:

window.Bundle = window.Bundle.default;

So now on you'll have :

// in script.jsvar bundle = new Bundle();

Sources

Standalone browserify builds