我正在尝试编写一个minify函数,可以根据文件类型使用minifiy html,css和js。我想使用现有的gulp插件进行这3个缩小过程来进行实际的缩小。我遇到的问题是我不知道如何在单个乙烯基文件上调用插件。以下是我到目前为止的情况:
var cssmin = require('gulp-cssmin');
var htmlmin = require('gulp-minify-html');
var uglify = require('gulp-uglify');
var minifiers = {
js: uglify,
css: cssmin,
html: htmlmin
};
function minify(options) {
var options = options || {};
return tap(function(file){
var fileType = file.path.split('.').pop();
options = options[fileType] || options
var minifier = minifiers[fileType];
if(!minifier)
console.error("No minifier for " + fileType + " - " + file.path);
// WHAT DO I DO HERE? This doesn't work but I want to do something similar
file.pipe(minifier(options));
});
}
我希望能够像这样调用minify函数:
gulp.src(['test.html', 'test.css', 'test.js'])
.pipe(minify());
答案 0 :(得分:4)
使用gulp-filter。
var gulpFilter = require('gulp-filter');
var jsFilter = gulpFilter('**/*.js');
var cssFilter = gulpFilter('**/*.css');
var htmlFilter = gulpFilter('**/*.html');
gulp.task('default', function () {
gulp.src('assets/**')
.pipe(jsFilter)
.pipe(uglify())
.pipe(jsFilter.restore())
.pipe(cssFilter)
.pipe(cssmin())
.pipe(cssFilter.restore())
.pipe(htmlFilter)
.pipe(htmlmin())
.pipe(htmlFilter.restore())
.pipe(gulp.dest('out/'));
});
也适用于单个文件,但是globs更具有前瞻性:)
答案 1 :(得分:2)
我最终使用gulp-filter来解决问题,但让它以可重用的方式工作却相当棘手。这是我的最终代码:
var cssmin = require('gulp-cssmin');
var htmlmin = require('gulp-htmlmin');
var uglify = require('gulp-uglify');
var lazypipe = require('lazypipe');
function getFilter(type) {
// create a filter for the specified file type
return filter('**/*.' + type);
}
var minify = function() {
var jsFilter = getFilter('js'),
cssFilter = getFilter('css'),
htmlFilter = getFilter('html');
var min = lazypipe()
.pipe(function(){return jsFilter;})
.pipe(uglify)
.pipe(jsFilter.restore)
.pipe(function(){return cssFilter;})
.pipe(cssmin)
.pipe(cssFilter.restore)
.pipe(function(){return htmlFilter;})
.pipe(htmlmin)
.pipe(htmlFilter.restore);
return min();
};
答案 2 :(得分:0)
要在单个文件上运行gulp插件,您需要执行以下操作:
var stream = minifier(options);
stream.once('data', function(newFile) {
file.contents = newFile.contents;
})
stream.write(file);