Ad

Require Not Defined With Gulp-browserify

- 1 answer

I'm trying to load modules in browser but I'm getting this error:

Uncaught ReferenceError: require is not defined

What I'm doing is creating the js in main.js and sending it over into the build as app.js

Here's my gulpfile.js

var browserify = require('gulp-browserify');
...
gulp.task('scripts', function() {
    gulp.src('src/scripts/main.js')
        .pipe(browserify({
          insertGlobals : true,
          debug : !gulp.env.production
        }))
        .pipe(gulp.dest('build/js'))
});
...
gulp.task('default', ['clean', 'concat', 'uglify', 'scripts']);

And my main.js

var fs = require('fs');
function getIt() {
var items = fs.readFileSync("../../data/data.json");
    var jsonItems = JSON.parse(items);
    console.log(jsonItems);
}
getIt();

How can I make this work in my template?

Ad

Answer

If you need external requires, you'll have to set the require property with the name of the file on the options object you pass to browserify. This will make browserify create the require function for you, so you can use later on use it outside the produced script.

 ...
 .pipe(browserify({
      insertGlobals : true,
      require : ['src/scripts/main.js'],
      debug : !gulp.env.production
    }))
  ...
Ad
source: stackoverflow.com
Ad