The original issue I was having was that the task was running x amount of times for the number of files existing inside src.pages
, I fixed this by adding the 'changed-in-place' plugin, to compare the last date modified of the source files. This meant that if the modified date hadn't changed, then it didn't run, or if it had changed then it would run, but only the necessary amount of times.
Because the plugin only checks files against the directory passed into the stream, it means it won't check against files inside src.templates
, which is essentially my .html partial files folder. The workaround I had running was to have a separate task watching for partial files changes, but not run any comparison functionality, this meant that I still had the original problem of the task running multiple times.
Updated: Here is a stripped down version of my gulpfile containing everything relevant to my question:
var fileFormat = 'html',
fileExt = '.' + fileFormat;
var src = {
pages: 'src/pages/**/*' + fileExt,
templates: 'src/templates/**/*' + fileExt,
};
var dist = {
pages: './',
css: './',
};
var config = {
templates: ['src/templates/', 'src/partials/'],
pagesWatch: './*' + fileExt, // Directory where pages are output
};
// Browser Sync with code/HTML injection
function bs() {
browserSync.use(htmlInjector, {
files: dist.pages + '*' + fileExt
});
browserSync.init({
server: dist.pages,
files: dist.css + '*.css',
watchOptions: {
awaitWriteFinish: {
stabilityThreshold: 500
}
}
});
}
function nunjucksPages() {
nunjucksRender.nunjucks.configure([src.templates]);
return gulp.src([src.pages])
.pipe(changedInPlace())
.pipe(nunjucksRender({
path: config.templates,
ext: fileExt
}))
.pipe(gulp.dest(dist.pages))
}
// Use CommonJS 'exports' module notation to declare tasks
exports.nunjucksPages = nunjucksPages;
exports.bs = bs;
function watch() {
gulp.watch([src.pages, src.templates], gulp.series(nunjucksPages));
gulp.watch(config.pagesWatch, gulp.series(htmlInjector));
}
// Runs all the required tasks, launches browser sync, and watches for changes
var build = gulp.series(clean, gulp.parallel(nunjucksPages));
var run = gulp.parallel(bs, watch);
gulp.task('default', gulp.series(build, run));
Edit for clarification: I have a task watching the pages and templates directory for changes, once it does, it runs the nunjucksPages
function. After the HTML has been compiled by nunjucks, browser sync will detect this and inject the HTML (the 2nd watch task in my code).
The current workaround I have in place is to duplicate both the nunjucks functions, and run them independently - the pages function with the caching (single reload, issue fixed!), and the templates function with no caching (reloading per X amount of pages).
Related issue and comment: https://github.com/carlosl/gulp-nunjucks-render/issues/47#issuecomment-240962074