从未知来源到同一目的地



我最近开始使用gulp来组织我的开发项目,但我遇到了一些我无法理解的小问题。这就是我的任务:

gulp.task('jsassemble', function () { 
   return gulp
   .src('vendor/proj/**/**/src/assets/js/*.js')
   .pipe(concat('all.js'))
  .pipe(gulp.dest('public/js'));
});

正如你所看到的,它会获取vendor/proj/anyFolder/anySubFolder/src/assets/js中的每个js文件,将它们放在一起,将新创建的js重命名为"all.js",然后将其放入public/js。问题是,我想用gullow来保持文件夹层次结构,例如:

源=供应商/proj/anyFolder1/anySubFolder1/src/assets/js/*.js
目标=public/js/anyFolder1/anySubFolder1/src/assets/js/all.js

源=供应商/proj/anyFolder1/anySubFolder2/src/assets/js/*.js
目标=public/js/anyFolder1/anySubFolder2/src/assets/js/all.js

而不是简单地将这些文件夹中的所有内容都放入一个1且唯一的public/js/all.js 中

有办法做吗?我试着先用谷歌搜索一下,但我没能用几个词正确地表达我的问题,得到了不想要的结果:/

您可以创建保持文件夹层次结构的函数。在此页面中(http://www.jamescrowley.co.uk/2014/02/17/using-gulp-packaging-files-by-folder/)你找到了解决方案。

var fs = require('fs');
var path = require('path');
var es = require('event-stream');
var gulp = require('gulp');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var scriptsPath = './src/scripts/';
function getFolders(dir){
    return fs.readdirSync(dir)
      .filter(function(file){
        return fs.statSync(path.join(dir, file)).isDirectory();
      });
}
gulp.task('scripts', function() {
   var folders = getFolders(scriptsPath);
   var tasks = folders.map(function(folder) {
      return gulp.src(path.join(scriptsPath, folder, '/*.js'))
        .pipe(concat(folder + '.js'))
        .pipe(gulp.dest(scriptsPath))
        .pipe(uglify())
        .pipe(rename(folder + '.min.js'))
        .pipe(gulp.dest(scriptsPath));
   });
   return es.concat.apply(null, tasks);
});

感谢@ccaballerog让我走上了正确的道路,下面是解释的代码:

//get every folder from a 'pathTo/Something'
function getFolders(dir){
   return fs.readdirSync(dir)
       return fs.statSync(path.join(dir, file)).isDirectory();
}

var projectsRoot = 'vendor/proj/';
var pathToJsFiles = '/src/assets/js/';
var pathToPublic = 'public/js/';
gulp.task('scripts', function() {
var sites = [];
var pathToProjects = [];
// Fetching every folders in vendor/proj
projects = getFolders(projectsRoot);
// Fetching every subfolder in vendor/proj/something
for(index in projects){
  sites.push(getFolders(projectsRoot + '/' + projects[index]));
}
// Pushing every projects/site that exists into an array
for(var i=0;i<projects.length;i++){
  for(var j=0; j<sites.length; j++)
    if(sites[i][j] != null)
      pathToProjects.push(projects[i] + '/' + sites[i][j]);
}
// Fetching every JS on vendor/proj/pathToAProject/pathToJsFiles
// concatenate them together
// and sending them to pathToPublic/pathToAProject/all.js
var tasks = pathToProjects.map(function(pathToAProject) {
   return gulp.src( projectsRoot + pathToAProject + pathToJsFiles + '/*.js')
    .pipe(concat('all.js'))
    .pipe(gulp.dest(pathToPublic + pathToAProject));
});
return es.concat.apply(null, tasks);
});

TL:DR=获取pathToPublic/someFolder/someFolder/PathToJS中的每个JS文件。

相关内容

  • 没有找到相关文章

最新更新