Run the gulp plugin in a single file

I am trying to write a minify function that can be used for minifiy html, css and js depending on the type of file. I would like to use existing gulp plugins for these 3 minimization processes to perform the actual minimization. The problem I am facing is that I don’t know what to name the plugin on one vinyl file. Here is what I still have:

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 as follows:

gulp.src(['test.html', 'test.css', 'test.js'])
    .pipe(minify());
+4
source share
3 answers

DECISION:

I decided to use gulp -filter to solve the problem, but it was pretty difficult to get it to work in reusable mode. Here is my last 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();
};
+2
source

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 :)

+4

To run the gulp plugin in 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);
0
source

Source: https://habr.com/ru/post/1531066/


All Articles