我最近开始使用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&#39 ;然后把它放在public / js中。问题是我想保留文件夹层次结构,例如:
Source = vendor / proj / anyFolder1 / anySubFolder1 / src / assets / js / * .js
Destination = public / js / anyFolder1 / anySubFolder1 / src / assets / js / all.js
Source = vendor / proj / anyFolder1 / anySubFolder2 / src / assets / js / * .js
Destination = public / js / anyFolder1 / anySubFolder2 / src / assets / js / all.js
而不是简单地将这些文件夹中的所有内容都放入1并且只有public / js / all.js
反正有吗?我已经尝试过谷歌了,但是我无法用几句话正确地表达我的问题而且给出了不想要的结果:/
答案 0 :(得分:0)
您可以创建保留文件夹层次结构的功能。在此页面(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);
});
答案 1 :(得分:0)
感谢@caballerog让我走上了正确的道路,这里是解释的代码:
//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文件。