保持文件夹结构与gulp中的concat()

时间:2016-10-08 12:56:01

标签: gulp gulp-concat

文件夹结构:

project
|
+-coffee
| |
| +-main.coffee
| |
| +-testDir
| | |
| | +-models.coffee
| | |
| | +-views.coffee
| |
| +-anotherDir
| | |
| | +-routes.coffee
| | |
| | +-views.coffee
| | |
| | +-modules.coffee
| |
| +- etc...
| 
+-www

这个想法是在将文件写入coffee/目录时保持文件夹结构不在www/目录中。 coffee/中可以有任意数量的子文件夹。每个文件夹中的所有.coffee个文件都应该连接到modules.js文件中:

www
|
+-modules.js
|
+-testDir
| |
| +-modules.js
|
+-anotherDir
| |
| +-modules.js
|
+- etc...

我目前有这个gulp任务:

gulp.task('coffee', function() {
    gulp.src('./coffee/**/*.coffee', {base: './coffee/'})
        .pipe(coffee({bare: true}).on('error', gutil.log))
        .pipe(uglify())
        // .pipe(concat('modules.js'))
        .pipe(gulp.dest('./www'))
});

如果没有concat(),文件将被放入正确的子文件夹中(但它们并未连接)。使用concat()所有文件都会连接到一个modules.js文件中:

www
|
+-modules.js

我如何才能正确认识到这一点?

1 个答案:

答案 0 :(得分:3)

以下是使用gulp-flatmap的解决方案:

var flatmap = require('gulp-flatmap');

gulp.task('coffee', function() {
  return gulp.src('./coffee/{*,}/', {base:'./coffee'})
    .pipe(flatmap(function(stream, dir) {
       return gulp.src(dir.path + '/*.coffee')
         .pipe(coffee({bare: true}).on('error', gutil.log))
         .pipe(uglify())
         .pipe(concat('modules.js'))
         .pipe(gulp.dest('./www/' + path.relative(dir.base, dir.path)))
     })) 
});

首先将coffee/目录及其所有直接子目录放入流中。然后,每个目录都会映射到一个新流,该流连接相应目录中的所有.coffee个文件。最后,使用path.relative()确定每个生成的modules.js文件的相应目标文件夹。

相关问题