mpen
mpen

Reputation: 283355

How to create a sub-pipe?

I want to create a "sub-pipe" such that I can create two different tasks that go through the same series of transformations but take different sources as input and write different files as output. e.g.,

gulp.task('styles', function() {
    return gulp.src(styles, {base: '.'})
        .pipe(MY_SUBPIPE_HERE('main.css'))
        .pipe(gulp.dest('public/css'))
});

gulp.task('login_styles', function() {
    return gulp.src(loginStyles, {base: '.'})
        .pipe(MY_SUBPIPE_HERE('login.css'))
        .pipe(gulp.dest('public/css'))
});

Here's what I'm trying:

function styleStream(filename) {
    return through.obj()
        .pipe(plumber())
        .pipe(sourcemaps.init({
            loadMaps: false,
            debug: debug,
        }))
        .pipe(wrapper({
            header: fileHeader,
        }))
        .pipe(gulpif(/\.less$/,less({
            strictMath: true,
            strictUnits: true,
        })))
        .pipe(concat(filename))
        .pipe(autoprefixer({ 
            browsers: ['last 2 versions', '> 1%', 'ie 8'],
            cascade: false // don't waste time on this
        }))
        .pipe(gulpif(!debug, minifyCss({
            compatibility: 'ie8',
        })))
        .pipe(sourcemaps.write('.', {
            includeContent: true,
            sourceRoot: '/',
            debug: debug,
        }))
        .pipe(plumber.stop());
}

But I think through.obj() is just emptying my pipe because nothing is coming through on the other end.

I don't know how to properly start to pipe so I can push stuff through it.

Upvotes: 0

Views: 109

Answers (1)

Heikki
Heikki

Reputation: 15417

Create a function that takes input / output parameters:

function styleFn(src, filename) {
    return function() {
        return gulp.src(src, {base: '.'})
            .pipe(plumber())
            .pipe(sourcemaps.init({
                loadMaps: false,
                debug: debug,
            }))
            .pipe(wrapper({
                header: fileHeader,
            }))
            .pipe(gulpif(/\.less$/,less({
                strictMath: true,
                strictUnits: true,
            })))
            .pipe(concat(filename))
            .pipe(autoprefixer({
                browsers: ['last 2 versions', '> 1%', 'ie 8'],
                cascade: false // don't waste time on this
            }))
            .pipe(gulpif(!debug, minifyCss({
                compatibility: 'ie8',
            })))
            .pipe(sourcemaps.write('.', {
                includeContent: true,
                sourceRoot: '/',
                debug: debug,
            }))
            .pipe(plumber.stop())
            .pipe(gulp.dest('public/css'));
    };
}

gulp.task('styles', styleFn(styles, 'main.css'));

gulp.task('login_styles', styleFn(loginStyles, 'login.css'));

Upvotes: 1

Related Questions