使用 Gulp.js 和 globbing 模式就地修改文件(同样的设置)

我有一个吞咽任务,试图转换。进入。Css 文件(使用 Gulp-ruby-sass) ,然后将生成的。把 css 文件放到它找到原始文件的相同位置。问题是,由于我使用的是 globbing 模式,我不一定知道原始文件存储在哪里。

在下面的代码中,我试图使用深入浅出的方法来接入流,并找出当前文件的文件路径,这个文件是从下面的代码中读取的:

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

如果有一个更简单的方法来做到这一点,我一定会更加欣赏这个解决方案。谢谢!

52129 次浏览

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("./"));

This is simpler than numbers1311407 has led on. You don't need to specify the destination folder at all, simply use .. Also, be sure to set the base directory.

gulp.src("sass/**/*.scss", { base: "./" })
.pipe(sass())
.pipe(gulp.dest("."));
gulp.src("sass/**/*.scss")
.pipe(sass())
.pipe(gulp.dest(function(file) {
return file.base;
}));

Originally answer given here: https://stackoverflow.com/a/29817916/3834540.

I know this thread is old but it still shows up as the first result on google so I thought I might as well post the link here.

This was very helpful!

gulp.task("default", function(){


//sass
gulp.watch([srcPath + '.scss', '!'+ srcPath +'min.scss']).on("change", function(file) {
console.log("Compiling SASS File: " + file.path)
return gulp.src(file.path, { base: "./" })
.pipe(sass({style: 'compressed'}))
.pipe(rename({suffix: '.min'}))
.pipe(sourcemaps.init())
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest("."));
});


//scripts
gulp.watch([srcPath + '.js','!'+ srcPath + 'min.js']).on("change", function(file) {
console.log("Compiling JS File: " + file.path)
gulp.src(file.path, { base: "./" })
.pipe(uglify())
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest("."));
});
})

if you want to save all files in their own path in the dist folder

const media = () => {
return gulp.src('./src/assets/media/**/*')
.pipe(gulp.dest(file => file.base.replace('src', 'dist'))
)
}


const watch = () => {
gulp.watch(
"./src/**/*",
media
);
};