Search code examples
javascriptnode.jsgulpr.js

Can a gulp plugin take in one file and return many files?


I am attempting to wrap the RequireJS Optimizer in a gulp plugin. There have been other attempts to provide this functionality in gulp but none of them meet my needs.

A common approach to plugin development is to take files in, process them, and then hand them out; however that approach is not really compatible with how the RequireJS Optimizer works.

While it does not meet the gulp plugin guidelines, I am working on a different approach of taking in the optimizer build configuration, processing it, and handing out the resulting file(s).

// Read in the r.js configuration
gulp.src( './build.js' )
    // Optimize the files according to the config
    .pipe( optimize() )
    // Return the resulting files for additional processing
    .pipe( size() );

Can a gulp plugin take in one file and return many files? If so, how?


Solution

  • I ended up using vinyl-fs to pass along the output of the optimization process.

    var requirejs   = require( 'requirejs' ),
        through     = require( 'through2' ),
        vfs         = require( 'vinyl-fs' );
    
    return through.obj( function( file, encoding, done ){
    
    // Parse config from file
    
    requirejs.optimize( config,
    
        // Success callback
        function( buildResponse ){
            vfs.src( config.dir + '/**/*.js' )
                .on( 'data', this.push.bind( this ) )
                .on( 'error', this.emit.bind( this, 'error' ) )
                .on( 'end', done );
        }.bind( this ),
    
        // Error callback
        function( buildError ){
            // Handle error
        } );
    

    Usages ends up looking like...

    // Read in build configuration
    gulp.src( 'build.js' )
        // Run files from the config through the optimizer
        .pipe( optimize( settings ) )
        // Measure the size of the optimized files
        .pipe( size() );