Reputation: 33
I am trying to split my gulpfile tasks into different files. I did it before and add it into main gulpfile by just adding require('./path/taskName')
But this is not working in gulp 4
this is my styles.js
file:
var gulp = require('gulp'),
postcss = require('gulp-postcss'),
autoprefixer = require('autoprefixer'),
cssvars = require('postcss-simple-vars'),
nestingCss = require('postcss-nested'),
cssImport = require('postcss-import');
function styles(){
console.log('Changes happened in CSS file');
return gulp.src('./public/styles/style.css')
.pipe(postcss([cssImport, cssvars, nestingCss, autoprefixer]))
.pipe(gulp.dest('./public/temp/styles'));
}
exports.styles = styles;
and this is my watch.js
file
var gulp = require('gulp'),
browserSync = require('browser-sync').create();
function html(done){
console.log('Changes happened in html');
browserSync.reload();
done();
}
function cssInject(){
return gulp.src('./public/temp/styles/style.css')
.pipe(browserSync.stream());
}
function watch(done){
browserSync.init({
server: {
baseDir: "public"
}
});
gulp.watch('./public/**/*.html', html);
gulp.watch('./public/styles/**/*.css', gulp.series(styles,cssInject));
done();
}
exports.html = html;
exports.watch = watch;
I added this into main gulpfile
require('./gulp/tasks/styles.js');
require('./gulp/tasks/watch.js');
but this is not working.It shows an error of
$ gulp watch
[20:27:30] Using gulpfile ~\Desktop\gulp-website\gulpfile.js
[20:27:30] Task never defined: watch
[20:27:30] To list available tasks, try running: gulp --tasks
Upvotes: 2
Views: 3476
Reputation: 51
You can still do it but in a different way:
With require-dir package (or you need index.js file where you export all your tasks: watch, html, styles):
// gulpfile.js
var tasksNotInAGulpfile = require('require-dir)('./gulp/tasks');
exports.watch = tasksNotInAGulpfile['watch'].watch
exports.styles = tasksNotInAGulpfile['styles].styles
...
The easiest solution for you:
// Main gulpfile (gulpfile.js)
var stylesTasks = require('./gulp/tasks/styles.js');
var watchTasks = require('./gulp/tasks/watch.js');
exports.styles = stylesTasks.styles;
exports.watch = watchTasks.watch;
exports.html = watchTasks.html;
For gulp to see your tasks they have to be exported with module.exports or exports like in the previous example.
Let me know if that helped.
Upvotes: 5