I'm trying to rebuild my gulp file to be a bit more efficient, and I'm having some trouble getting my styles
task to only compile if a file has changed.
I found this question, but the answer doesn't seem to be working for me.
Let's say I have my repo organized like so:
/dev
/assets
/styles
all.css
/src
/assets
/styles
all.scss
_header.scss
gulpfile.js
package.json
I only want to overwrite all.css
if a change has been made in either of my Sass files. So, if I where to save _header.scss
but no changes had been made, and ran my styles
task, it should realize that the code hasn't changed and not overwrite all.css
.
I was looking at gulp-cached, per the question I linked to above, but that doesn't seem to be working for me. Here's the task at it's most basic:
var gulp = require("gulp"),
cached = require("gulp-cached"),
sass = require("gulp-sass");
gulp.task("styles", function() {
return gulp.src(src + "/assets/styles/all.scss")
.pipe(sass().on("error", sass.logError))
.pipe(cached("sass_compile")) // should skip the dest if cache is the same
.pipe(gulp.dest(dev + "/assets/styles"));
});
The cached
pipe doesn't seem to be working in this instance. I run gulp styles
and it still overwrites all.css, even if no changes have been made, even if I didn't even re-save the file.
The more complex task I'd eventually like to use is:
var gulp = require("gulp"),
cached = require("gulp-cached"),
sourcemaps = require("gulp-sourcemaps"),
sass = require("gulp-sass"),
autoprefixer = require("gulp-autoprefixer"),
// set up environment paths
src = "./src",
dev = "./dev",
dist = "./dist";
gulp.task("styles", function() {
return gulp.src(src + "/assets/styles/all.scss")
.pipe(sourcemaps.init())
.pipe(sass().on("error", sass.logError))
.pipe(autoprefixer("last 2 version", "ie 8", "ie 9"))
.pipe(sourcemaps.write())
.pipe(cached("sass_compile")) // should skip the dest if cache is the same
.pipe(gulp.dest(dev + "/assets/styles"));
});
Would greatly appreciate some guidance on this. Thanks much.
EDIT 1: Note that all.scss
in this demo only contains @import "_header";
.
EDIT 2: Okay, I just figured out that gulp-cached
seems to be working fine in a watch
task. So revised question: How can I get this same type of functionality outside of the watch task?
gulp-newer solved this problem, it can check imported files. Pretty awesome! Here's my final styles task: