Gulp处理文件名

时间:2014-05-21 23:08:42

标签: javascript concatenation gulp stylus

我如何使用gulp.src中的文件名,让我们说基于这些文件名在内存文件中创建,并将该流管道传递给其他文件名?

假设我想获取所有*.styl个文件,并将找到的每个文件路径推送到内存文件中,并以@import作为前缀,然后将该流传输到stylus编译器。像这样的东西:

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

我找不到任何让你阅读和合并手写笔文件的好包装,所以我想也许我可以用某种方式解决这个问题?

可能我最终会遇到范围界定,样式优先和破坏特异性规则的问题,但我需要将我的样式合并到一个文件中

1 个答案:

答案 0 :(得分:5)

我使用以下代码创建了一个github repo以提供帮助。 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
});

为我们制作的mix gulp-plugin创建一个新文件(为了清晰的代码)。

mixer.js 是本地gulp-plugin,用于获取文件名,然后将名称转换为Vinyl文件,我们将该文件发送到手写笔。

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

在结束时,我正在考虑将其移至完整的gulp插件,如果它将被使用。