我在使用 Gulp 时遇到过很多同样的问题,因为管道传输到多个目的地的各种任务似乎很困难,或者可能是不可能的。此外,为一项任务设置多个流似乎效率低下,但我想这是目前的解决方案。
对于我当前的项目,我需要将多个捆绑包与各个页面相关联。修改 Gulp 启动器
https://github.com/greypants/gulp-starter
browserify/watchify 任务:
https://github.com/dtothefp/gulp-assemble-browserify/blob/master/gulp/tasks/browserify.js
我在 glob 模块回调中使用了一个 forEach 循环:
gulp.task('browserify', function() {
var bundleMethod = global.isWatching ? watchify : browserify;
var bundle = function(filePath, index) {
var splitPath = filePath.split('/');
var bundler = bundleMethod({
// Specify the entry point of your app
entries: [filePath],
// Add file extentions to make optional in your requires
extensions: ['.coffee', '.hbs', '.html'],
// Enable source maps!
debug: true
});
if( index === 0 ) {
// Log when bundling starts
bundleLogger.start();
}
bundler
.transform(partialify)
//.transform(stringify(['.html']))
.bundle()
// Report compile errors
.on('error', handleErrors)
// Use vinyl-source-stream to make the
// stream gulp compatible. Specifiy the
// desired output filename here.
.pipe(source( splitPath[splitPath.length - 1] ))
// Specify the output destination
.pipe(gulp.dest('./build/js/pages'));
if( index === (files.length - 1) ) {
// Log when bundling completes!
bundler.on('end', bundleLogger.end);
}
if(global.isWatching) {
// Rebundle with watchify on changes.
bundler.on('update', function(changedFiles) {
// Passes an array of changed file paths
changedFiles.forEach(function(filePath, index) {
bundle(filePath, index);
});
});
}
}
// Use globbing to create multiple bundles
var files = glob('src/js/pages/*.js', function(err, files) {
files.forEach(function(file, index) {
bundle(process.cwd() + '/' + file, index);
})
});
});