简体   繁体   中英

require not defined with gulp-browserify

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?

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
    }))
  ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM