問題描述
我有一個 gulp 任務,它試圖將 .scss 文件轉換為 .css 文件(使用 gulp-ruby-sass),然后將生成的 .css 文件放到它找到原始文件的同一位置.問題是,由于我使用的是通配模式,我不一定知道原始文件的存儲位置.
I have a gulp task that is attempting to convert .scss files into .css files (using gulp-ruby-sass) and then place the resulting .css file into the same place it found the original file. The problem is, since I'm using a globbing pattern, I don't necessarily know where the original file is stored.
在下面的代碼中,我嘗試使用 gulp-tap 進入流并找出讀取流的當前文件的文件路徑:
In the code below I'm trying to use gulp-tap to tap into the stream and figure out the file path of the current file the stream was read from:
gulp.task('convertSass', function() {
var fileLocation = "";
gulp.src("sass/**/*.scss")
.pipe(sass())
.pipe(tap(function(file,t){
fileLocation = path.dirname(file.path);
console.log(fileLocation);
}))
.pipe(gulp.dest(fileLocation));
});
根據 console.log(fileLocation)
的輸出,這段代碼看起來應該可以正常工作.但是,生成的 CSS 文件似乎比我預期的要高一個目錄.它應該是 project/sass/partials
的地方,結果文件路徑只是 project/partials
.
Based on the output of the console.log(fileLocation)
, this code seems like it should work fine. However, the resulting CSS files seem to be placed one directory higher than I'm expecting. Where it should be project/sass/partials
, the resulting file path is just project/partials
.
如果有更簡單的方法可以做到這一點,我肯定會更加欣賞該解決方案.謝謝!
If there's a much simplier way of doing this, I would definitely appreciate that solution even more. Thanks!
推薦答案
正如你所懷疑的,你把這弄得太復雜了.目的地不需要是動態的,因為全局路徑也用于 dest
.只需通過管道連接到您從中獲取 src 的同一基本目錄,在本例中為sass":
As you suspected, you are making this too complicated. The destination doesn't need to be dynamic as the globbed path is used for the dest
as well. Simply pipe to the same base directory you're globbing the src from, in this case "sass":
gulp.src("sass/**/*.scss")
.pipe(sass())
.pipe(gulp.dest("sass"));
如果您的文件沒有共同的基礎并且您需要傳遞一個路徑數組,那么這已經不夠了.在這種情況下,您需要指定基本選項.
If your files do not have a common base and you need to pass an array of paths, this is no longer sufficient. In this case, you'd want to specify the base option.
var paths = [
"sass/**/*.scss",
"vendor/sass/**/*.scss"
];
gulp.src(paths, {base: "./"})
.pipe(sass())
.pipe(gulp.dest("./"));
這篇關于使用 Gulp.js 和 globbing 模式就地修改文件(相同的目標)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!