gulp打包编译速度优化
保持对新技术的好奇心,深入研究当前工作使用的技术,同时进行一些输出,例如写博客,做开源,研究分享,写书等的,没有输出的学习就是耍流氓。 ——来自知乎
做项目时使用了browserify,但每次修改编译时间都很长,十几秒的样子?反正感觉等待编译的时间已经远远超过了修改代码的时间,忍无可忍之时,开始寻找解决方案。
于是很快就找到了watchify,简单理解,就是增量编译。
修改之前:
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var streamify = require('gulp-streamify');
gulp.task('browserify', function () {
var bundleStream = browserify('v1/js/app.js').bundle();
return bundleStream
.pipe(source('app.js'))
.pipe(streamify(uglify()))
.pipe(gulp.dest('./dev/js/'));
});
// after each change, execute browserify, make a long long progress...
gulp.task('release', ['browserify'], function () {
return gulp.src('./dev/js/app.js')
.pipe(gulp.dest('../static/js/'));
});
// watch everything
gulp.task('watch', function () {
gulp.watch(['v1/less/**/*'], ['css2js']);
gulp.watch(['v1/js/**/*'], ['release']);
});
...
gulp.task('default', ['release', 'watch']);
添加watchify:
var watchify = require('watchify');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var streamify = require('gulp-streamify');
var assign = require('lodash.assign');
var bundleStream = watchify(browserify(assign({}, watchify.args, {
// required for watchify
cache: {},
// required for watchify
packageCache: {},
entries: ['v1/js/app.js']
})));
gulp.task('browserify', bundle);
// on any dep update, runs the bundler
bundleStream.on('update', bundle);
// output build logs to terminal
bundleStream.on('log', gutil.log);
function bundle() {
return bundleStream.bundle()
// log errors if they happen
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source('app.js'))
.pipe(streamify(uglify()))
.pipe(gulp.dest('./dev/js/'));
}
// browserify will not need
gulp.task('release', function () {
return gulp.src('./dev/js/app.js')
.pipe(gulp.dest('../static/js/'));
});
gulp.task('watch', function () {
gulp.watch(['v1/less/**/*'], ['css2js']);
// just watch one file produced by WATCHIFY
gulp.watch(['./dev/js/app.js'], ['release']);
});
...
// only at the beginning browserify being executed
gulp.task('default', ['browserify', 'watch']);
延伸阅读及参考资料:
http://csspod.com/advanced-tips-for-using-gulp-js/
http://csspod.com/using-browserify-with-gulp/