Gulp 4 watch runs only 1 time - javascript

As I mentioned in the title there is a problem running gulp.watch. It runs watch only after first change in the file, when I changing second, third and etc it doesn't run task.
Below is my gulpfile.js:
var gulp = require('gulp');
var babel = require('gulp-babel');
var rename = require("gulp-rename");
var del = require('del');
var less = require('gulp-less');
gulp.task('es6', function () {
return gulp.src('./test.js')
.pipe(rename(function (path) {
path.basename += "-es6";
return path;
}))
.pipe(babel())
.pipe(gulp.dest('./'))
});
gulp.task('clean', function () {
return del('./test-es6.js');
});
gulp.task('watch', function () {
gulp.watch( './test.js', gulp.series('es6') );
console.log('Running watch...');
});
gulp.task('default', gulp.series('clean', 'es6', gulp.parallel('watch') ));
And some logs :
$: gulp
[14:22:40] Using gulpfile /var/www/html/es2015/gulpfile.js
[14:22:40] Starting 'default'...
[14:22:40] Starting 'clean'...
[14:22:40] Finished 'clean' after 11 ms
[14:22:40] Starting 'es6'...
[14:22:43] Finished 'es6' after 2.11 s
[14:22:43] Starting '<parallel>'...
[14:22:43] Starting 'watch'...
Running watch...
[14:22:55] Starting '<series>'...
[14:22:55] Starting 'es6'...
[14:22:55] Finished 'es6' after 42 ms
[14:22:55] Finished '<series>' after 43 ms << first change, but no second third and etc.
I used similar configuration in couple of projects and it was fine, everything worked.
I don't know if this information is important, but I'm using Ubuntu 14.04

After long trying I found a solution for this problem.
I don't know why but this configuration works on Windows, but as appeared on Ubuntu I had to add ** to path of the watched file this part of code:
gulp.task('watch', function () {
gulp.watch( './**/test.js', gulp.series('es6') );
console.log('Running watch...');
});

Related

Ordering of tasks in a gulpfile

I want to implement very simple chain of tasks in my project by Gulp:
Copy all files;
Replace some placeholders with values;
Minify some
files;
And for these purposes I have created gulpfile with such main task:
gulp.task(tasks.build, [
tasks.simplyCopy,
tasks.minifyXml,
tasks.minifyJs,
tasks.subst]);
It's a pretty simple and self describable.
Below I wrote full gulpfile.js:
var gulp = require('gulp');
var prettyData = require('gulp-pretty-data');
var uglify = require('gulp-uglify');
var renvy = require('gulp-renvy');
var tasks = {
simplyCopy: "simply-copy",
minifyXml: "minify-xml",
minifyJs: "minify-js",
subst: "renvy-subst",
build: "build"
};
// Collection of tasks
gulp.task(tasks.build, [tasks.simplyCopy, tasks.minifyXml, tasks.minifyJs,
tasks.subst]);
// By this task sources simply copy to the destination
var destination = 'dist/';
gulp.task(tasks.simplyCopy, function () {
gulp.src(['Source/**/*.*', '!Source/www/res/strings/*.*'], {base:
'Source/www'})
.pipe(gulp.dest(destination));
});
var stringsDestPath = 'dist/res/strings/';
var stringSrcPath = 'Source/www/res/strings/';
// By this task some xml files minify
gulp.task(tasks.minifyXml, [tasks.simplyCopy], function() {
gulp.src(stringSrcPath + '*.xml')
.pipe(prettyData({
type: 'minify',
preserveComments: true,
extensions: {
'xlf': 'xml',
'svg': 'xml'
}
}))
.pipe(gulp.dest(stringsDestPath))
});
var placeholder = {
'%version%': {'prod':'010.00', 'dev':'010.00'}
};
// By this task in some files placeholders replaces with value
gulp.task(tasks.subst, [tasks.minifyXml, tasks.minifyJs], function(){
return gulp.src(stringsDestPath + '*.*')
.pipe(renvy(placeholder, 'dev'))
.pipe(gulp.dest(stringsDestPath));
});
// By this task some js files minify
gulp.task(tasks.minifyJs, [tasks.simplyCopy], function () {
gulp.src(stringSrcPath + '*.js')
.pipe(uglify())
.pipe(gulp.dest(stringsDestPath))
});
But I have such unexpected behavior:
replacing of placeholders is not happening, but it's executes.
[16:29:51] Using gulpfile C:\PDDirectory\Workspace\src\some_workbench\User_Part\gulpfile.js
[16:29:51] Starting 'simply-copy'...
[16:29:51] Finished 'simply-copy' after 17 ms
[16:29:51] Starting 'minify-xml'...
[16:29:51] Finished 'minify-xml' after 7.49 ms
[16:29:51] Starting 'minify-js'...
[16:29:51] Finished 'minify-js' after 5.84 ms
[16:29:51] Starting 'renvy-subst'...
[16:29:51] Finished 'renvy-subst' after 28 ms
[16:29:51] Starting 'build'...
[16:29:51] Finished 'build' after 5.66 ?s
Task tasks.subst executed sepparetly works fine, but in a chain with other tasks, I see results of executing copy and minify only.
Why so?
Place tasks.subst has the sole dependency for tasks.build
gulp.task(tasks.build, [tasks.subst]);
Since tasks.subst requires all the others, the ordering should be correct and adding all the other tasks may lead to ordering problems.
From the gulp.task documentation:
Note: Are your tasks running before the dependencies are complete?
Make sure your dependency tasks are correctly using the async run
hints: take in a callback or return a promise or event stream.
To ensure that a task dependencies are fulfilled before executing it, Gulp needs each task to return a stream or a promise, or call the task function callback parameter.
In your case, the following task should just return the stream:
tasks.minifyXml
tasks.minifyJs
tasks.simplyCopy
For example:
gulp.task(tasks.minifyXml, [tasks.simplyCopy], function(done) {
// just return the task stream here
return gulp.src(stringSrcPath + '*.xml')
.pipe(prettyData({
// ...
}))
.pipe(gulp.dest(stringsDestPath));
});
or using the callback when it's not possible to return a stream:
gulp.task('somename', function(done) {
// async function which does not return a stream like other gulp functions
getFilesAsync(function(err, res) {
// pass any errors to the callback
if (err) return done(err);
var stream = gulp.src(res)
.pipe(minify())
.pipe(gulp.dest('build'))
.on('end', done); // use the callback when it's done
});
});

Gulp error: watch task has to be a function

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.

gulp-protractor e2e task fails to run

Update: Seems like this is a bug in gulp-protractor. On their github page they filed it as a bug and will take a look into it. Source: https://github.com/mllrsohn/gulp-protractor/issues/64
Only possible workaround you can do until the bug is resolved is change the directory of your project to something that doesn't include spaces.
So I'm trying to get an Aurelia project started including front end unit testing. Here is where the problem starts. When I try to run the e2e gulp task I get the following error:
[10:45:44] using gulpfile ~\Documents\Visual Studio 2013\Projects\ProjectX\ProjectX\gulpfile.js
[10:45:44] Starting 'build-e2e'...
[10:45:44] Finished 'build-e2e' after 207 ms
[10:45:44] Starting 'e2e'...
'C:\Users\jorisd\Documents\Visual' is not recognized as an internal or external command, operable program or batch file.
C:\Users\jorisd\Documents\Visual Studio 2013\Projects\ProjectX\ProjectX\build\tasks\e2e.js:34
.on('error', function(e) {throw e; });
Error: protractor exited with code 1
Basically it's the highlighted code that has the problem. Since my path includes a space, it'll stop there for some reason.
Here's how my e2e.js file looks like right now:
var gulp = require('gulp');
var paths = require('../paths');
var to5 = require('gulp-babel');
var plumber = require('gulp-plumber');
var webdriverUpdate = require('gulp-protractor').webdriver_update;
var webdriverStandalone = require("gulp-protractor").webdriver_standalone;
var protractor = require('gulp-protractor').protractor;
// for full documentation of gulp-protractor,
// please check https://github.com/mllrsohn/gulp-protractor
gulp.task('webdriver-update', webdriverUpdate);
gulp.task('webdriver-standalone', ['webdriver-update'], webdriverStandalone);
// transpiles files in
// /test/e2e/src/ from es6 to es5
// then copies them to test/e2e/dist/
gulp.task('build-e2e', function() {
return gulp.src(paths.e2eSpecsSrc)
.pipe(plumber())
.pipe(to5())
.pipe(gulp.dest(paths.e2eSpecsDist));
});
// runs build-e2e task
// then runs end to end tasks
// using Protractor: http://angular.github.io/protractor/
gulp.task('e2e', ['build-e2e'], function(cb) {
return gulp.src(paths.e2eSpecsDist + '/*.js')
.pipe(protractor({
configFile: '/protractor.conf.js',
args: ['--baseUrl', 'http://127.0.0.1:9000']
}))
.on('end', function() { process.exit(); })
.on('error', function(e) { throw e; });
});
The problem is situating in the e2e task with the configFile option.
I tried change the line into the following:
configFIle: __dirname + '/protractor.conf.js',
But this aswell without result. If any of you know a workaround for including spaces in the configFile path, I'll be happy to hear it.
For me its working fine.
var angularProtractor = require('gulp-angular-protractor');
gulp.task('test', function (callback) {
gulp
.src([__dirname+'/public/apps/adminapp/**/test/**_test.js'])
.pipe(angularProtractor({
'configFile': 'public/apps/adminapp/app.test.config.js',
'debug': false,
'args': ['--suite', 'adminapp'],
'autoStartStopServer': true
}))
.on('error', function(e) {
console.log(e);
})
.on('end',callback);
});

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