Why does Gulp fail to automatically re-process my

2019-04-26 17:34发布

In my gulpfile.js, JS changes automatically trigger both BrowserSync reload and my JS processing task. But for some reason, although the reload does work, my JS task fails to correctly process JS changes and create new JS file in dist/ folder. I have to restart Gulp for that. Why?

Gulpfile.js:

var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');

gulp.task('sass', function() {
  return gulp.src('../assets/styles/**/*.scss')
  .pipe(sass())
  .pipe(gulp.dest('../dist/styles'))
  .pipe(browserSync.reload({
    stream: true
  }))
});

gulp.task('js', function() {
  return gulp.src(['../assets/scripts/*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(concat('main.js'))
    .pipe(uglify())
    .pipe(gulp.dest('../dist/scripts'))
});

gulp.task('browserSync', function() {
  browserSync.init({
    proxy: 'http://127.0.0.1/my_site/new-front-page/',
  })
})

gulp.task('watch', ['sass', 'js', 'browserSync'], function() {
  gulp.watch('../assets/styles/**/*.scss',['sass']);
  gulp.watch('../**/**/*.php', browserSync.reload);
  gulp.watch('../assets/scripts/*.js', browserSync.reload);
  gulp.watch('../*.html', browserSync.reload);
});

EDIT:

Also tried the code below for the "js" task (see the 3 last lines compared to the code above), to no avail:

gulp.task('js', function() {
  return gulp.src(['../assets/scripts/*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(concat('main.js'))
    .pipe(uglify())
    .pipe(gulp.dest('../dist/scripts'))
    .pipe(browserSync.reload({
      stream: true
    }))
});

7条回答
相关推荐>>
2楼-- · 2019-04-26 18:40

Your gulp.watch for js changes does not actually call your 'js' task. That is why you have to rerun the 'watch' task to see any changes.

gulp.watch('../assets/scripts/*.js', browserSync.reload);

It just reloads the browser but doesn't call the 'js' task. Change to:

gulp.watch('../assets/scripts/*.js', ['js']);

and

gulp.task('js', function() {
  return gulp.src(['../assets/scripts/*.js'])
  .pipe(jshint())
  .pipe(jshint.reporter('default'))
  .pipe(concat('main.js'))
  .pipe(uglify())
  .pipe(gulp.dest('../dist/scripts'))
  .pipe(browserSync.reload({ stream:true }));
});
查看更多
登录 后发表回答