我正在使用带有 browserify 和 factor-bundle 的 gulp。 我有以下代码:
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'));
我想在 parial 包(“build/a.js”和“build/b.js”)上传递一些操作(如 uglify、bundle-collapser 或其他作业)。我尝试使用因子捆绑页面上描述的方法:
b.plugin('factor-bundle', { outputs: [ write('x'), write('y') ] });
function write (name) {
return concat(function (body) {
console.log('// ----- ' + name + ' -----');
console.log(body.toString('utf8'));
});
}
但是我不懂 write() 方法,不知道如何执行 uglification 以及如何 gulp.dest 得到结果。
任何想法?解释?
最佳答案
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'))
});
}
你会这样使用它:
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'))
使用 factor-bundle
插件会影响 browserify 之后的输出
.bundle()
被调用。通常,它会将 bundle 生成为可读流
映射到您的每个条目文件,然后您就可以进一步申请
对它们进行转换。
相反,您将获得一个包含 bundle 的可读流
从提供的条目文件中共享公共(public)模块,我称之为
common.js
在上面的例子中。然后你需要处理转换
分别映射到每个入口文件的可读流。
在上面的示例中,我已将可写流添加到输出数组,排列 与我的入口文件的顺序相同,它们接收各自的 bundle 可读流并对它们应用进一步的转换
您还可以利用 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'));
我认为值得注意的是,将进一步的下游工作应用于输出 完全脱离管道。因此,如果您使用 gulp 并返回 来自 browserify 的流,任务会提前完成,因为 它仍然会在入口文件上执行操作。我没有遇到 这个问题还没有。
希望这会有所帮助。
关于javascript - 对因子捆绑的部分捆绑进行一些操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28191918/