Fahad Shaikh
Fahad Shaikh

Reputation: 327

gulp watch finished immediately

I am new to gulp and learning it through youtube tutorials. I got stuck on gulp watch command which should keep track of my js file but it's not working. I have found many similar questions on StackOverflow but none helped me.

This is my code

Package.json

{
  "name": "gulp-tutorial",
  "version": "1.0.0",
  "description": "This is gulp tutorial",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "gulpfile",
    "scss",
    "js"
  ],
  "author": "Fahad Shaikh",
  "license": "GPL-3.0",
  "devDependencies": {
    "gulp": "^4.0.2",
    "gulp-autoprefixer": "^7.0.1",
    "gulp-rename": "^1.4.0",
    "gulp-sass": "^4.0.2",
    "gulp-sourcemaps": "^2.6.5",
    "gulp-watch": "^5.0.1"
  }
}

gulpfile.js

var gulp =  require('gulp');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var watch = require('gulp-watch');

var jsDIST = './dist/js/';

gulp.task('js', function () {
   return gulp.src(jsSRC)
       .pipe(gulp.dest(jsDIST));
});

gulp.task('default', gulp.series('js'));

gulp.task('watch', gulp.series('default'), function () {
   gulp.watch('./src/js/**/*.js', ['js']);
});

According to tutorials and documents on the internet I shouldn't have got back the control of CLI after running gulp watch but I can run another command as soon as my watch task is finished.

Upvotes: 0

Views: 551

Answers (1)

Mark
Mark

Reputation: 181248

Since you are using gulp v4, try this instead:

 // you don't need this and you aren't using it anyway
 // var watch = require('gulp-watch');

var jsDIST = './dist/js/';

// gulp.task('js', function () {
//   return gulp.src(jsSRC)
//       .pipe(gulp.dest(jsDIST));
// });

function js() {
  return gulp.src(jsSRC)
     .pipe(gulp.dest(jsDIST));
}

// your main problem was in this task
// gulp.task('watch', gulp.series('default'), function () {
//  gulp.watch('./src/js/**/*.js', ['js']);  // array is incorrect in gulp v4
// });

function watch() {
   gulp.watch('./src/js/**/*.js', js);  
};

// gulp.task('default', gulp.series('js'));  // 'taskName must be in quotes'
gulp.task('default', gulp.series(js, watch));       //  functionName not in quotes

Now you can run it with just gulp command and nothing else.

Upvotes: 1

Related Questions