1

Is there a way to change gulp context inside my gulpfile.js?

Right now I'm prefixing all my gulp.src with the location I want. But is there a way to change this globally?

This is the current code I have:

var base = '../';
gulp.task('copy', function() {
   gulp.src(base + 'sampleFile.js').pipe(gulp.dest('dist/'));
});

gulp.task('clean', function() {
   del.sync([base + options.dist]);
});

This is somehow what I'm looking for:

gulp.base('../', function() {
    gulp.task('copy', function() {
       gulp.src('sampleFile.js').pipe(gulp.dest('dist/'));
    });

    gulp.task('clean', function() {
       del.sync([options.dist]);
    });
});
Alan Souza
  • 7,475
  • 10
  • 46
  • 68
  • 1
    Have you tried looking at that: http://stackoverflow.com/questions/27236437/set-working-directory-in-gulpfile-js -- It has a somewhat different approach, but should do the same – ddprrt Mar 27 '15 at 09:28
  • Thanks @ddprrt, in that post there is a reference for process.chdir, which indeed solved my problem! – Alan Souza Mar 28 '15 at 23:04

2 Answers2

0

The CLI flag --cwd will let you change it globally -- though to do what you want you will also need to give it the location of your gulpfile in the directory you're calling it from, so

gulp --gulpfile gulpfile.js --cwd ../

will replace the path prefixes you have.

You can also create an options object for your gulp.src calls with cwd: base on them:

var opts = {cwd: '..'}

gulp.task('copy', function() {
   gulp.src('sampleFile.js', opts).pipe(gulp.dest('dist/'));
});

It may also make sense to move your Gulpfile into a directory where it can more obviously access what it will be reading and writing to.

max
  • 5,979
  • 2
  • 21
  • 16
  • Thanks for your answer @max. It does solve the problem but I don't think it is an acceptable solution in my case. I'm writing a library with gulp tasks, and the location vary, so I cannot move it to the proper location. I can added opts, but I would have to do it for every single 'src' that I have. The one that sounds more suitable is the CLI. But I would have to inform this to the consumer of my library (which is undesired). Sorry, I should have explained better my need. – Alan Souza Mar 28 '15 at 23:00
0

Based on the comment of @ddprrt, I was able to find the solution.

The idea is to use process.chdir to navigate to a different location. The updated code is like follows:

if (options.base) {
   process.chdir(options.base);
}

gulp.task('copy', function() {
   gulp.src('sampleFile.js').pipe(gulp.dest('dist/'));
});

gulp.task('clean', function() {
   del.sync([options.dist]);
});
Alan Souza
  • 7,475
  • 10
  • 46
  • 68