問題描述
有沒有辦法在 gulpfile 中設置 Gulp 的工作目錄,這樣我就可以從子目錄運行 gulp 命令而不會遇到任何問題?我對此進行了搜索,但沒有找到我要查找的內容.
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'
};
我想做這樣的事情:
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'
};
我想知道 Gulp 是否公開了這個功能.也許節點本身允許這樣做.
I'm wondering if Gulp exposes this functionality. Perhaps node itself allows this.
(我意識到當我運行命令時可能有一種方法可以自己執行命令行,但我想將它包含在 gulp 文件中,特別是出于分發目的.我希望 gulp 的工作目錄與gulpfile 所在的目錄.)
(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.)
謝謝!
推薦答案
你應該使用 path.join 因為它會處理正確的斜線,并且按照該路徑您可以添加一個快捷方式:
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'));
或者,你可以:
gulp.src(..., {cwd: __dirname})
gulp.dest(..., {cwd: __dirname})
類似:
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);
};
看這里和這里.
這篇關于在 gulpfile.js 中設置工作目錄?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!