在Gulp任务中获取相关源/目标 [英] Getting relative source/destination in Gulp task
问题描述
假设我在 /Users/me/app/src/scripts/foo.js
处有一个文件。我将这个文件写入 /Users/me/app/dist/scripts/foo.js
:
Let's say I have a file at /Users/me/app/src/scripts/foo.js
. I set up a gulp tasks that writes this file to /Users/me/app/dist/scripts/foo.js
:
gulp.src('src/scripts/foo.js', base: 'src')
.pipe(...)
.pipe(gulp.dest('dist'))
我在写一个简单的插件,需要知道脚本/ foo.js
。我希望 file.relative
是这个部分路径,但它提供了 foo.js
。我没有看到从 file.path
,<$的任意组合获取 scripts / foo.js
的方法c $ c> file.cwd , file.base
等。
I'm writing a simple plugin and need to know scripts/foo.js
. I was expecting file.relative
to be this partial path, but instead it provides foo.js
. I don't see a way to get scripts/foo.js
from any combination of file.path
, file.cwd
, file.base
, etc.
我可以得到我需要的路径的一部分吗?
How can I get the part of the path I need?
推荐答案
假设您想要相对于您指定基地的路径,想要使用类似node的路径模块来进行提取:
Assuming that you want the path relative to your specified base, you would want to use something like node's path module to do the extraction:
var path = require('path');
// this is how you get the relative path from a vinyl file instance
path.relative(path.join(file.cwd, file.base), file.path);
以下是一个使用示例的gulpfile示例:
Here is an example gulpfile using your example:
var path = require('path'),
gulp = require('gulp'),
through = require('through2');
function parsePath() {
return through.obj(function (file, enc, cb) {
console.log(file.base);
console.log(file.cwd);
console.log(file.path);
console.log(path.relative(path.join(file.cwd, file.base), file.path))
cb();
});
}
gulp.task('default', function () {
gulp.src('src/scripts/foo.js', { base: 'src'})
.pipe(parsePath())
.pipe(gulp.dest('dist'));
});
以下是我运行这个gulpfile时的输出:
Here is the output when I run this gulpfile:
src
/Volumes/Data/Project/sandbox/gulp-ex
/Volumes/Data/Project/sandbox/gulp-ex/src/scripts/foo.js
scripts/foo.js
这里是项目文件夹结构 p>
Here is the project folder structure
gulp-ex/
|_ gulpfile.js
|_ src/scripts/foo.js
|_ dist
这篇关于在Gulp任务中获取相关源/目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!