Set working directory in gulpfile.js?

2020-07-11 07:22发布

问题:

Is there a way to set the working directory for Gulp within a gulpfile, so that I can run a gulp command from a subdirectory without running into any issues? I ran a search for this and didn't find what I was looking for.

To clarify, I'm aware of adding a prefix to the files I'm using. However, instead of this -

var gulp = require('gulp');
var jshint = require('gulp-jshint');
...

var paths = {
    js: [__dirname + 'app/*/*.js', __dirname + '!app/lib/**'],
    css: __dirname + 'app/*/*.styl',
    img: __dirname + 'app/img/*',
    index: __dirname + '*.html',
    dist: __dirname + 'dist'
};

I'd like to do something like this:

var gulp = require('gulp');
var jshint = require('gulp-jshint');
...

gulp.cwd(__dirname); // This would be much easier to understand, and would make future edits a bit safer.

var paths = {
    js: ['app/*/*.js', '!app/lib/**'],
    css: 'app/*/*.styl',
    img: 'app/img/*',
    index: '*.html',
    dist: 'dist'
};

I'm wondering if Gulp exposes this functionality. Perhaps node itself allows this.

(I realize that there is likely a way to do command line itself when I run the command, but I would like to include it in the gulp file, especially for distribution purposes. I want the working directory for gulp to match the directory in which the gulpfile resides.)

Thanks!

回答1:

Instead of concatenating strings by yourself, you should be using path.join since it will take care of the proper slash, and following that path you can add a shorcut:

var path = require('path'),
    p    = function () {

    Array
        .prototype
        .unshift
        .call(arguments, __dirname);

    return path.join.apply(path, arguments);
};

console.log(p('a', 'b', 'c'));

Or, well, you can just:

gulp.src(..., {cwd: __dirname})
gulp.dest(..., {cwd: __dirname})

Something like:

var src = function (globs, options) {

    options = options || {};
    options.cwd = __dirname;

    return gulp.src(globs, options);
};

var dest = function (folder, options) {

    options = options || {};
    options.cwd = __dirname;

    return gulp.dest(folder, options);
};

Look here and here.



回答2:

Besides option.cwd, you can also use process.chdir(yourDir)

it could be used anywhere in a gulpfile. e.g.

process.chdir(yourDir);
var gulp = require('gulp');

Make sure your gulp is up-to-date( > 3.8.10), this may not work in older gulp.