Search code examples
javascriptnode.jsgulpbrowserify

How to programatically loops through files and require each one?


I'm in Node (gulp actually) trying to programatically loop through files and require each one. But I keep getting an error that Browserify doesn't have a pipe method. This doesn't happen when I explicitely write each require statement. Here's my code:

var bStream = browserify({
         entries: [options.JSX_DEST + '/main']
     })
     .require('react')
     .require('react-addons');

fs.readdirSync(options.JSX_DEST).forEach(function(file){
        bStream.require(options.JSX_DEST + '/' + file);
    });

bStream.bundle({debug: false});
bStream.pipe(source('bundle.js'))
    .pipe(gulp.dest(options.JSX_DEST));

Any ideas on the correct way to do this? Just for clarification the following works if I chain my bundle statement in the first line but this requires I explicitly write each require line whereas I want to do it programatically.

var bStream = browserify({
        entries: [options.JSX_DEST + '/main']
    })  
    .require('react')
    .require('react-addons')
    .bundle({debug: false});
    bStream
    .pipe(source('bundle.js'))
    .pipe(gulp.dest(options.JSX_DEST));

Solution

  • You are forgetting to assign the result of the function call back to bstream:

    fs.readdirSync(options.JSX_DEST).forEach(function(file){
        bStream = bStream.require(options.JSX_DEST + '/' + file);
    });
    
    bStream.bundle({debug: false});
      .pipe(source('bundle.js')) // <- call .pipe on the result of .bundle!
      .pipe(gulp.dest(options.JSX_DEST));
    

    Just to be clear, if you use method chaining such as

    var x = foo().bar().baz();
    

    then the equivalent version without chaining would be

    var x = foo();
    x = x.bar();
    x = x.baz();
    

    not

    var x = foo();
    x.bar();
    x.baz();
    

    Notice that x would still have the value that foo() returned, not the value that baz() returned.