Last Updated: February 25, 2016
·
4.031K
· stevelacy

gulp: Get a list of CSS file names as @imports

I created an answer for this SO question and am sharing it here in detail.

Problem:
A large folder structure has several .css files ( this works for: .styl, .sass, .less as well).
One main file should have a list of all files as @imports.

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()) // preprocessor
  .pipe(gulp.dest('./out'));  // the out folder
});

We will then create a mini gulp plugin for getting the list of css files as paths.

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

It gets all file paths and pushes it into a variable which will convert each path into an @import.

From then the output can be processed into a dest folder, or pushed to a preprocessor plugin.

Note: The final file extension is modified with the preprocessor.

An example repo for this project can be seen here: https://github.com/stevelacy/gulp-mix-test