iLemming
iLemming

Reputation: 36166

Gulp proccessing filenames

How can I use filenames from gulp.src and let's say create in memory file based on those filenames, and pipe that stream to something else?

Let's say I want to get all *.styl files and push every single filepath found, into in-memory file prefixing it with @import, and then pipe that stream into stylus compiler. something like this:

gulp.src('./src/**/*.styl',{read:false})
.pipe(function(filename){
      return "@import '"+filename+"'"
 })
 .pipe(streamify())
 .pipe(stylus())
 .pipe( gulp.dest('./bin/combined.css'));

I couldn't find any good package that let's you read and combine stylus files, so I thought maybe I can solve this somehow?

Probably I'd end up having problems with scoping, style precedence and broken specificity rules, but I need to combine my styles into one file

Upvotes: 1

Views: 1394

Answers (1)

SteveLacy
SteveLacy

Reputation: 4163

I created a github repo with the following code to assist. https://github.com/stevelacy/gulp-mix-test

gulpfile.js

var gulp = require('gulp');
var stylus = require('gulp-stylus');
var mixer = require('./mixer');  // our local gulp-plugin


gulp.task('mix', function(){
  gulp.src('./src/**/*.styl')
  .pipe(mixer("outfile"))  // the out file name, no extension
  .pipe(stylus())
  .pipe(gulp.dest('./out'));  // the out folder
});

Create a new file (for clarity of code) for the mixing gulp-plugin we will make.

mixer.js is the local gulp-plugin for getting the file names and then concating the names into a Vinyl file which we will send down the stream to stylus.

mixer.js

var through = require('through2');
var gutil = require('gulp-util');


module.exports = function(outname){
  var paths = '';  // where we will push the path names with the @import

  var write = function (file, enc, cb){
    if (file.path != "undefined"){
      paths =  paths + '\n' + '@import "' + file.path + '"';
    }
    cb();
  };

  var flush = function(cb){  // flush occurs at the end of the concating from write()
    gutil.log(gutil.colors.cyan(paths));  // log it

    var newFile = new gutil.File({  // create a new file
      base: __dirname,
      cwd: __dirname,
      path: __dirname + '/' + outname + '.styl',
      contents: new Buffer(paths)  // set the contents to the paths we created
    });

    this.push(newFile);  // push the new file to gulp's stream
    cb();
  };

  return through.obj(write, flush);  // return it
};

At the conclusion of this I am considering moving this to a full gulp plugin, if it will be used.

Upvotes: 5

Related Questions