Gulp error: watch task has to be a function - javascript

Here is my gulpfile:
// Modules & Plugins
var gulp = require('gulp');
var concat = require('gulp-concat');
var myth = require('gulp-myth');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var imagemin = require('gulp-imagemin');
// Styles Task
gulp.task('styles', function() {
return gulp.src('app/css/*.css')
.pipe(concat('all.css'))
.pipe(myth())
.pipe(gulp.dest('dist'));
});
// Scripts Task
gulp.task('scripts', function() {
return gulp.src('app/js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
// Images Task
gulp.task('images', function() {
return gulp.src('app/img/*')
.pipe(imagemin())
.pipe(gulp.dest('dist/img'));
});
// Watch Task
gulp.task('watch', function() {
gulp.watch('app/css/*.css', 'styles');
gulp.watch('app/js/*.js', 'scripts');
gulp.watch('app/img/*', 'images');
});
// Default Task
gulp.task('default', gulp.parallel('styles', 'scripts', 'images', 'watch'));
If I run the images, scripts or css task alone it works. I had to add the return in the tasks - this wasn't in the book but googling showed me this was required.
The problem I have is that the default task errors:
[18:41:59] Error: watching app/css/*.css: watch task has to be a function (optionally generated by using gulp.parallel or gulp.series)
at Gulp.watch (/media/sf_VM_Shared_Dev/webdevadvlocal/gulp/public_html/gulp-book/node_modules/gulp/index.js:28:11)
at /media/sf_VM_Shared_Dev/webdevadvlocal/gulp/public_html/gulp-book/gulpfile.js:36:10
at taskWrapper (/media/sf_VM_Shared_Dev/webdevadvlocal/gulp/public_html/gulp-book/node_modules/undertaker/lib/set-task.js:13:15)
at bound (domain.js:287:14)
at runBound (domain.js:300:12)
at asyncRunner (/media/sf_VM_Shared_Dev/webdevadvlocal/gulp/public_html/gulp-book/node_modules/async-done/index.js:36:18)
at nextTickCallbackWith0Args (node.js:419:9)
at process._tickCallback (node.js:348:13)
at Function.Module.runMain (module.js:444:11)
at startup (node.js:136:18)
I think it is because there is also no return in the watch task. Also the error message isn't clear - at least to me. I tried adding a return after the last gulp.watch() but that didn't work either.

In gulp 3.x you could just pass the name of a task to gulp.watch() like this:
gulp.task('watch', function() {
gulp.watch('app/css/*.css', ['styles']);
gulp.watch('app/js/*.js', ['scripts']);
gulp.watch('app/img/*', ['images']);
});
In gulp 4.x this is no longer the case. You have to pass a function. The customary way of doing this in gulp 4.x is to pass a gulp.series() invocation with only one task name. This returns a function that only executes the specified task:
gulp.task('watch', function() {
gulp.watch('app/css/*.css', gulp.series('styles'));
gulp.watch('app/js/*.js', gulp.series('scripts'));
gulp.watch('app/img/*', gulp.series('images'));
});

GULP-V4.0
It is a bit late to answer this right now but still. I was stuck in this problem as well and this is how I got it working.
In detail analysis what I was doing wrong
I forgot to call the reload function when the watch noticed some changes in my html files.
Since fireUp and KeepWatching are blocking. They need to be started in parallel rather than serially. So I used the parallel function in the variable run.

thanks for all
gulp.task('watch', function(){
gulp.watch('app/sass/**/*.sass', gulp.series('sass'));
});
for version gulp 4.xx

It worked for me in Gulp 4.0
gulp.task('watch', function() {
gulp.watch('src/images/*.png', gulp.series('images'));
gulp.watch('src/js/*.js', gulp.series('js'));
gulp.watch('src/scss/*.scss', gulp.series('css'));
gulp.watch('src/html/*.html', gulp.series('html'));
});

//Check what worked for me
gulp.task('watch', function(){
gulp.watch('css/shop.css', gulp.series(['shop']));
});

In my case, work for me this:
(in gulpfile.js)
(install: gulp, gulp sass)
var gulp = require('gulp');
var sass = require('gulp-sass')(require('sass'));
var cssDest = 'style';
var cssInputFile = 'source/style.scss';
var watchedFiles = 'source/**/*.scss';
gulp.task('buildcss', function(){
return gulp.src(cssInputFile)
.pipe(sass({
outputStyle: 'compressed'
}))
.pipe(gulp.dest(cssDest));
});
gulp.task('watch', function(){
gulp.watch(watchedFiles, gulp.series(['buildcss']));
});
Commend: gulp watch
(v 4.0)

On my side, I also had to add "{usePolling: true}" this to get it working:
gulp.watch(paths.js_src + '/*.js', {usePolling: true}, gulp.series(projectScripts, ondemandProjectScripts))
I think it's because my code runs into a docker container.

Related

Gulp watch only detects the first change

I am working on gulp and implementing watch functionality. But the gulp watch detects the changes only for the first time.
I want to write the code so that it detects the changes in CSS and JS files and performs minification and concatenation on the development environment.
I am using the following code:
var gulp = require('gulp');
var concat = require('gulp-concat');
var clean_css = require('gulp-clean-css');
var uglify = require('gulp-uglify');
gulp.task('style', function(){
gulp.src(['assets/css/style.css', 'assets/css/custom.css'])
.pipe(concat('build.min.css'))
.pipe(clean_css())
.pipe(gulp.dest('assets/build'));
});
gulp.task('script', function(){
gulp.src(['assets/js/jquery.js', 'assets/js/custom.js'])
.pipe(concat('build.min.js'))
.pipe(uglify())
.pipe(gulp.dest('assets/build'));
});
gulp.task('watch', function(){
gulp.watch('assets/css/*.css', gulp.series('style') );
gulp.watch('assets/js/*.js', gulp.series('script'));
});
This is probably because gulp does not know the task has finished the first time so it will not re-start the task again when you modify a file next. This can be solved just by adding return statements to your tasks:
gulp.task('style', function(){
return gulp.src(['assets/css/style.css', 'assets/css/custom.css'])
.pipe(concat('build.min.css'))
.pipe(clean_css())
.pipe(gulp.dest('assets/build'));
});
gulp.task('script', function(){
return gulp.src(['assets/js/jquery.js', 'assets/js/custom.js'])
.pipe(concat('build.min.js'))
.pipe(uglify())
.pipe(gulp.dest('assets/build'));
});

Gulp errors trying to get uglify and default gulp to work

hi I'm having trouble setting up gulp it seems to have all changed since I last used it
I'm getting errors and can't figure out why. I'll post some pics along with my code. the first problem is that uglify doesn't complete and the second problem is that gulp default won't run the command prompt should explain my problems better than I can if you have any further questions please ask and be civil.
var gulp = require('gulp');
var sass = require('gulp-sass');
var uglifycss = require('gulp-uglifycss');
sass.compiler = require('node-sass');
gulp.task('sass', function () {
return gulp.src('./Edit/sass/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./Edit/css'));
});
gulp.task('css', function () {
gulp.src('./Edit/css/*.css')
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(gulp.dest('./upload/css'));
});
gulp.task('run',['sass','css']);
gulp.task('watch', function(){
gulp.watch('./Edit/sass/*.scss',['sass']);
gulp.watch('./Edit/css/*.css',['css']);
});
gulp.task('default',['watch', 'run']);
here is my output
So you've got two kinds of errors going on:
1. Task function must be specified
The way gulp runs dependent tasks has changed in v4.0.0. Instead of specifying those tasks in an array, like this:
gulp.task('run',['sass','css']);
They've introduced the gulp.series and gulp.parallel functions. A task function, and not an array, because Task function must be specified. In your case, that gives:
gulp.task('run', gulp.series('sass','css'));
2. Did you forget to signal async completion
This one you could have found, given that this question has been asked many times now. You need to add a return statement to your css task for gulp to know when it's completed and can thus move on. Your task becomes:
gulp.task('css', function () {
return gulp.src('./Edit/css/*.css')
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(gulp.dest('./upload/css'));
});
Result:
Putting it all together, you get this gulpfile:
var gulp = require('gulp');
var sass = require('gulp-sass');
var uglifycss = require('gulp-uglifycss');
sass.compiler = require('node-sass');
gulp.task('sass', function () {
return gulp.src('./Edit/sass/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./Edit/css'));
});
gulp.task('css', function () {
return gulp.src('./Edit/css/*.css')
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(gulp.dest('./upload/css'));
});
gulp.task('run', gulp.series('sass','css'));
gulp.task('watch', function(){
gulp.watch('./Edit/sass/*.scss',gulp.series('sass'));
gulp.watch('./Edit/css/*.css', gulp.series('css'));
});
gulp.task('default', gulp.series('watch', 'run'));
Note that you can combine your sass and css task if you'd like:
gulp.task('styles', function(){
return gulp.src('./Edit/sass/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(uglifycss({
"maxLineLen": 80,
"uglyComments": true
}))
.pipe(gulp.dest('./upload/css'));
});

AssertionError [ERR_ASSERTION]: Task function must be specified

I am attempting to refactor some legacy code I wrote 2 years ago. A gulpfile.js file to be precise.
It seems like the problem is here:
// gulp.task('default', ['browserify', 'copy'], function() {
// return gulp.watch('src/**/*.*', ['browserify', 'copy']);
// });
I commented it out and replaced it with this:
gulp.task('default', gulp.series('browserify', 'copy'), function() {
return gulp.watch('src/**/*.*', ['browserify', 'copy']);
});
Not good enough. The whole file looks like this:
var gulp = require('gulp');
var browserify = require('browserify');
var reactify = require('reactify'); // Converts jsx to js
var source = require('vinyl-source-stream'); // Converts string to a stream
gulp.task('browserify', function() {
browserify('./src/js/main.js')
.transform('reactify')
.bundle()
.pipe(source('main.js'))
.pipe(gulp.dest('dist/js'));
});
gulp.task('copy', function() {
gulp.src('src/index.html').pipe(gulp.dest('dist'));
gulp.src('src/css/*.*').pipe(gulp.dest('dist/css'));
gulp.src('src/images/*.*').pipe(gulp.dest('dist/images'));
gulp.src('src/js/vendors/*.*').pipe(gulp.dest('dist/js'));
});
// gulp.task('default', ['browserify', 'copy'], function() {
// return gulp.watch('src/**/*.*', ['browserify', 'copy']);
// });
gulp.task('default', gulp.series('browserify', 'copy'), function() {
return gulp.watch('src/**/*.*', ['browserify', 'copy']);
});
I have read through some of the getting started documentation, but what I have read thus far has not helped me refactor this.
With Gulp 4.0 the way you run tasks in series has got changed. You can read and get what you want using below link
https://github.com/gulpjs/gulp/blob/master/docs/recipes/running-tasks-in-series.md.
This issue faced me because of the version of gulp I installed using npm i gulp
to solve this quickly, downgrade to that gulp version you used before 2 years and everything will work fine.

gulp will not output js min file

Cant seem to find my problem here. After I run Gulp, the all-css.min.css gets outputted to _build folder but the JS will not go! am I missing something? Cant seem to find what is making this not work.
var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var minifyHTML = require('gulp-minify-html');
var sourcemaps = require('gulp-sourcemaps');
var minifyCSS = require('gulp-minify-css');
var inlineCss = require('gulp-inline-css');
var rev = require("gulp-rev");
var del = require('del');
var jsBase = {
src: [
'/Scripts/Core/ko.bindinghandlers-1.0.0.js',
'/Scripts/Twitter/typeahead-0.10.2.js',
'/Scripts/LdCore/mobile-core.js',
'/Scripts/LDCore/Chat.js',
'/Scripts/unsure.js' // These have any unknown lines in them.
]
};
gulp.task('clean', function () {
del.sync(['_build/*'])
});
gulp.task('produce-css', function () {
return gulp.src(cssBase.src)
.pipe(minifyCSS({ keepBreaks: false }))
.pipe(concat('all-css.min.css'))
.pipe(gulp.dest('_build/'))
});
gulp.task('produce-minified-js', function () {
return gulp.src(jsBase.src)
//.pipe(sourcemaps.init())
//.pipe(uglify())
.pipe(concat('all.min.js'))
//.pipe(rev()) // adds random numbers to end.
//.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('_build/'));
});
gulp.task('default', ['clean'], function () {
gulp.start('produce-css', 'produce-minified-js');
});
According to Contra at this post, we shouldn't be using gulp.start.
gulp.start is undocumented on purpose because it can lead to
complicated build files and we don't want people using it
Bad:
gulp.task('default', ['clean'], function () {
gulp.start('produce-css', 'produce-minified-js');
});
Good:
gulp.task('default', ['clean','produce-css','produce-minified-js'], function () {
// Run the dependency chains asynchronously 1st, then do nothing afterwards.
});
It's totally legit to have nothing in the gulp.task, as what it's doing is running the dependency chains asynchronously & then terminating successfully.
You could also do the following:
gulp.task('default', ['clean','produce-css','produce-minified-js'], function (cb) {
// Run a callback to watch the gulp CLI output messages.
cb();
});
Since Gulp creates "Starting default" on the CLI, this would help to display "Finished default" in the CLI after everything else runs.

Creating a Gulp task but not working, why?

according to the Gulp Docs, and according to what I see, I have everything fine.
Before, lets say a week ago, I was doing ctrl + s on Sublime Text and my view(browser) reload automatically. Now, after some merges with master branch, those tasks are not working anymore, nothing is reloading and I have to go to my console and do Gulp every time I want to see changes and I hate that. I am going to paste my gulpfile.js here so maybe you have an answer for me
var gulp = require('gulp'),
watch = require('gulp-watch'),
gutil = require('gulp-util'),
bower = require('bower'),
concat = require('gulp-concat'),
sass = require('gulp-sass'),
autoprefixer = require('gulp-autoprefixer'),
minifyCss = require('gulp-minify-css'),
rename = require('gulp-rename'),
sh = require('shelljs'),
jshint = require('gulp-jshint'),
jscs = require('gulp-jscs'),
shell = require('gulp-shell'),
uglify = require('gulp-uglify'),
ngAnnotate = require('gulp-ng-annotate');
var paths = {
sass: ['./scss/**/*.scss']
};
// Dev task
gulp.task('dev', ['sass', 'lint', 'compress-lib', 'compress-js', 'run-ionic'], function() { });
// Build task
gulp.task('default', ['dev']);
//Ionic Serve Task
gulp.task('run-ionic',shell.task([
'ionic serve'
]));
gulp.task('compress-lib', function() {
gulp.src([
'./www/lib/ionic/js/ionic.bundle.min.js',
'./www/lib/localforage/dist/localforage.min.js',
'./www/lib/lodash/lodash.min.js',
'./www/lib/moment/moment.js',
'./www/lib/validator-js/validator.min.js',
'./www/lib/localforage-wrapper/localforage-wrapper.js',
'./www/lib/ua-parser-js/dist/ua-parser.min.js'
])
.pipe(concat('lib.min.js'))
.pipe(gulp.dest('./www/js'))
});
gulp.task('compress-js', function() {
gulp.src([
'./www/js/app.js',
'./www/js/controllers.js',
'./www/js/common/footerController.js',
'./www/js/common/sportsFilter.js',
'./www/js/common/searchBarDirective.js',
'./www/js/auth/controller.js',
'./www/js/auth/service.js',
'./www/js/auth/interceptor.js',
'./www/js/auth/logoutController.js',
'./www/js/sports/controller.js',
'./www/js/sports/service.js',
'./www/js/leagues/service.js',
'./www/js/lines/controller.js',
'./www/js/lines/service.js',
'./www/js/betSlip/controller.js',
'./www/js/betSlip/service.js',
'./www/js/deviceDetector/service.js'
])
.pipe(ngAnnotate())
.pipe(concat('code.min.js'))
.pipe(gulp.dest('./www/js'))
});
// JSHint task
gulp.task('lint', function() {
gulp.src(['www/js/*.js', 'www/js/**/*.js', '!www/js/lib.min.js', '!www/js/code.min.js'])
.pipe(jscs())
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('sass', function(done) {
gulp.src('./scss/ionic.app.scss')
.pipe(sass({onError: function(e) { console.log(e); } }))
.pipe(autoprefixer('last 2 versions', 'Chrome', 'ios_saf','Android'))
.pipe(gulp.dest('./www/css/'))
.pipe(minifyCss({
keepSpecialComments: 0
}))
.pipe(rename({ extname: '.min.css' }))
.pipe(gulp.dest('./www/css/'))
.on('end', done);
});
gulp.task('watch', function() {
gulp.watch(paths.sass, ['sass']);
});
gulp.task('install', ['git-check'], function() {
return bower.commands.install()
.on('log', function(data) {
gutil.log('bower', gutil.colors.cyan(data.id), data.message);
});
});
gulp.task('git-check', function(done) {
if (!sh.which('git')) {
console.log(
' ' + gutil.colors.red('Git is not installed.'),
'\n Git, the version control system, is required to download Ionic.',
'\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
'\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
);
process.exit(1);
}
done();
});
all I need is the reloading part back, every time I save -- ctrl + s something in my IDE, I want to see the changes in the browser automatically, I am wasting a lot of my time by going to the console and typing gulp everty time I want to see changes.
you should check when the gulpfile changed in git, then diff the two versions to see what changed.
$ git log gulpfile.js
$ git diff <commit id> gulpfile.js
In regards to the browser not refreshing, it's likely an issue with LiveReload. Check your watchPatterns config in the ionic.project file.
https://github.com/driftyco/ionic-cli#testing-in-a-browser
As for gulp not running after you change a file:
It sounds like someone may have moved some files around. Confirm that this path still points to the files you want to watch:
sass: ['./scss/**/*.scss']. If it's not, update it and run gulp watch.
Keep in mind that gulp.watch() can't detect new files, so it will need to be restarted every time a new watchable file is created.

Categories