简体   繁体   中英

make some operations on factor-bundle's partial bundles

I am using gulp with browserify and factor-bundle. I have the following code:

b = browserify({
        entries: [ 'a.js', 'b.js'],
        plugin: [ [ 'factor-bundle', { outputs: [ 'build/a.js', 'build/b.js' ] } ] ]
    })
    .bundle()
    .pipe(source('bundle.js'))
    .pipe(buffer())
    .pipe(gulp.dest('/build/common'));

I want to pipe some actions (like uglify, bundle-collapser or other job) on the parial bundles ('build/a.js' and 'build/b.js'). I tried to use the method described on the factor-bundle's page:

b.plugin('factor-bundle', { outputs: [ write('x'), write('y') ] });
function write (name) {
    return concat(function (body) {
        console.log('// ----- ' + name + ' -----');
        console.log(body.toString('utf8'));
    });
}

But I don't understand the write() method and don't know how to perform uglification and how to gulp.dest the result.
Any idea? explanation?

The write() method returns a writable stream that allows you to pipe bundles generated by the factor-bundle plugin through further downstream transformations.

For instance, your write() method may look something like this:

var path = require('path');
var file = require('gulp-file');
var sourcemaps = require('gulp-sourcemaps');

function write (filepath) {    
    return concat(function (content) {        
        // create new vinyl file from content and use the basename of the
        // filepath in scope as its basename.
        return file(path.basename(filepath), content, { src: true })
        // uglify content
        .pipe(uglify())
        // write content to build directory
        .pipe(gulp.dest('./build/scripts'))        
    });
}

And you would use it like this:

browserify({
    entries: [ 'a.js', 'b.js'],
    plugin: [ [ 'factor-bundle', { outputs: [ write('a.js'), write('b.js') ] } ] ]
})
.bundle()
.pipe(write('common.js'))
// Could have use these instead, but it wouldn't be as DRY.
// .pipe(source('common.js'))
// .pipe(uglify())
// .pipe(gulp.dest('./build/scripts'))

Using the factor-bundle plugin affects the output of browserify after .bundle() is called. Normally, it would generate bundles as readable streams mapping to each of your entry files, then you would be able to apply further transformations to them.

Instead you will get a single readable stream that contains a bundle with the shared common modules from the supplied entry files, which I have called common.js on the example above. Then you need to handle the transfomations of the readable streams that map to each entry file separately.

In the example above I have added writable streams to the outputs array, arranged in the same order as my entry files, which receive their respective bundle as readable stream and apply further transformations to them

You could also leverage the factor.pipeline event :

var b = browserify({ ... });

b.on('factor.pipeline', function (id, pipeline) {
    pipeline.get('wrap').push(write(id));
});

b.plugin(factor);

return b.bundle().pipe(write('common.js'));

I think it is worth noting that applying further downstream work to the outputs is completely detached from the pipeline. So if you were using gulp and returned the stream from browserify, the task would have completed prematurely because it would still be performing operations on the entry files. I haven't run into issues with this yet.

Hope this helps.

This is a bit old, but it might be usefull to someone else. The answer above from @Christian helped me, but i had to solve the issue of the task completion. I did it by adding a counter for opened streams, and calling the task callback once they are all closed.

gulp.task('build:js:compile', function(cb) {

const apps  = getAllJavascriptFilesPaths(); // this returns an array of full path to the js files i want to bundle
const dist  = 'dist'; // the output path

const files = [];
const streams = [];
let openedStreams = 0;

// We use browserify factor-bundle to get the shared code in a separated js file, and not in all apps files
// The write function here handles the post processing of each browserified app by returning a writable stream
// We check the number of opened streams, and call the callback once they are all closed, to be sure the task is
// complete
function write(filepath) {
    openedStreams++;
    return concat(function (content) {
        // create new vinyl file from content and use the basename of the
        // filepath in scope as its basename.
        return file(path.basename(filepath), content, { src: true })
            .pipe(uglify())
            .pipe(gulp.dest(dist))
            .on('finish', function () {
                openedStreams--;
                if (openedStreams == 0) {
                    cb();
                }
            });
    });
}

apps.forEach(function (file) {
    files.push(file);
    streams.push(write(file)));
});

browserify(files)
    .plugin(factor, { outputs: streams })
    .transform("babelify", {presets: 'babel-preset-env'})
    .bundle()
    .pipe(write('common.js'));
});

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