Вопрос

I'm trying to write a minify function that can be used to minifiy html, css, and js depending on file type. I would like to use the existing gulp plugins for these 3 minification processes to do the actual minification. The problem I'm having is I don't know how to call a plugin on a single vinyl file. Here is what I have so far:

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));
    });
}

I would like to be able to call the minify function like this:

gulp.src(['test.html', 'test.css', 'test.js'])
    .pipe(minify());
Это было полезно?

Решение 2

SOLUTION:

I ended up using gulp-filter to solve the issue, but it was fairly tricky to get it working in a reusable way. Here is my final code:

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();
};

Другие советы

Use 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/'));
});

Will work for single files too but globs are more futureproof :)

To run gulp plugin on a single file you need to do the following:

var stream = minifier(options);

stream.once('data', function(newFile) {
    file.contents = newFile.contents;
})

stream.write(file);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top