对factor-bundle的部分包进行一些操作

Nao*_*aor 9 javascript node.js browserify gulp factor-bundle

我正在使用浏览器和factor-bundle.我有以下代码:

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'));
Run Code Online (Sandbox Code Playgroud)

我想在parial包('build/a.js'和'build/b.js')上管理一些动作(比如uglify,bundle-collapser或其他工作).我尝试使用factor-bundle页面上描述的方法:

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

但我不理解write()方法,也不知道如何执行uglification以及如何gulp.dest结果.
任何的想法?说明?

小智 11

write()方法返回一个可写流,允许您通过进一步的下游转换来管道由factor-bundle插件生成的包.

例如,您的write()方法可能如下所示:

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'))        
    });
}
Run Code Online (Sandbox Code Playgroud)

你会像这样使用它:

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'))
Run Code Online (Sandbox Code Playgroud)

使用factor-bundle插件会在.bundle()调用后影响browserify的输出 .通常,它会生成捆绑包作为映射到每个条目文件的可读流,然后您就可以对它们应用进一步的转换.

相反,您将获得一个可读的流,其中包含来自所提供的条目文件的共享公共模块的包,我common.js在上面的示例中调用了该文件 .然后,您需要分别处理映射到每个条目文件的可读流的转换.

在上面的示例中,我将可写流添加到输出数组,按照与我的条目文件相同的顺序排列,它们将各自的包接收为可读流并对它们应用进一步的转换

您还可以利用此factor.pipeline 事件:

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'));
Run Code Online (Sandbox Code Playgroud)

我认为值得注意的是,将更多下游工作应用于产出完全脱离了管道.因此,如果您使用gulp并从browserify返回流,则该任务将过早完成,因为它仍将对条目文件执行操作.我还没有遇到过这方面的问题.

希望这可以帮助.