antesoles
antesoles

Reputation: 683

Using parent directory of file-directory as destination in gulp

How can I use the parent directory of a file-directory of a wildcard source in gulp?

Source files:

|gulpfile.js (just to show where the base is)
|elements/foundations/A/js/src/mainA.js
|elements/foundations/A/js/src/subA.js
|elements/foundations/B/js/src/mainB.js
...
|elements/foundations/F/js/src/mainF.js

Desired target/result:

|elements/foundations/A/js/mainA.min.js
|elements/foundations/A/js/subA.min.js
|elements/foundations/B/js/mainB.min.js
...
|elements/foundations/F/js/mainF.min.js

I've tried different approaches, but eventually none of them worked.

This one runs without errors but doesn't generate any files.

gulp.task('scripts', function () {
    return gulp.src('./elements/foundations/**/js/src/*.js', {base: './elements/foundations/**/'})
            .pipe(rename({suffix: '.min'}))
//          .pipe(uglify()) and others ...
            .pipe(gulp.dest('./'))
            ;
});

This one generates files, but directly in the src directory.

gulp.task('scripts', function () {
    return gulp.src('./elements/foundations/**/js/src/*.js', {base: './elements/foundations/'})
            .pipe(rename({suffix: '.min'}))
            .pipe(gulp.dest('./elements/foundations/'))
            ;
});

And if I try to use the wildcard (**) in the destination, gulp ends up in an infinite loop (independently of the position of the wildcard).

gulp.task('scripts', function () {
    return gulp.src('./elements/foundations/**/js/src/*.js', {base: './elements/foundations/'})
            .pipe(rename({suffix: '.min'}))
            .pipe(gulp.dest('./elements/foundations/**/'))
            ;
});

I've also tried to use it without setting the base, but the results were similar.

Upvotes: 2

Views: 2057

Answers (1)

Sven Schoenung
Sven Schoenung

Reputation: 30574

You can pass a function to gulp-rename for more complex renaming operations. This allows you for example to use the path module of node.js to manipulate file paths:

var gulp = require('gulp');
var rename = require('gulp-rename');
var path = require('path');

gulp.task('scripts', function() {
   return gulp.src('./elements/foundations/**/js/src/*.js')
     .pipe(rename(function(file) {
        file.dirname = path.dirname(file.dirname);
        file.basename = file.basename + '.min';
        return file;
     }))
//   .pipe(uglify()) and others ...
     .pipe(gulp.dest('./elements/foundations/'))
});

Upvotes: 3

Related Questions