-1

I am using google-closure-compiler and gulp to minify my angularjs files.

Here is my gulpfile code;

var closureCompiler = require('google-closure-compiler').gulp();
var flatmap = require('gulp-flatmap');
var path = require('path');

gulp.task('js-closure', function () {
    return gulp.src(['app/js/*.js', 'dist/single.js'], {base: './'})
        .pipe(flatmap(function(stream, file) {
            return stream.pipe(closureCompiler({
                compilation_level: 'SIMPLE_OPTIMIZATIONS',
                warning_level: 'QUIET',
                language_in: 'ECMASCRIPT6_STRICT',
                language_out: 'ECMASCRIPT5_STRICT',
                output_wrapper: '(function(){\n%output%\n}).call(this)',
                js_output_file: path.basename(file.path).replace(/js$/, 'min.js')
            }))
        }))
        .pipe(gulp.dest('./dist/js'));
});

The code works fine. However, I have to run gulp js-closure manually on the command-line to compile the js files.

I would like to compile the js files automatically whenever any one of the js files are changed.

EDIT: gulp-watch seems to be a good fit for this problem https://www.npmjs.com/package/gulp-watch. How can the code be modified to use gulp-watch? Any good sample examples?

Chad Killingsworth
  • 14,360
  • 2
  • 34
  • 57
guagay_wk
  • 26,337
  • 54
  • 186
  • 295

2 Answers2

1

Straight from the gulp api docs:

var watcher = gulp.watch(['app/js/*.js', 'dist/single.js'], ['js-closure']);
watcher.on('change', function(event) {
  console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
});
Chad Killingsworth
  • 14,360
  • 2
  • 34
  • 57
1

As you indicated, using gulp-watch is the right approach. A simple change would be adequate.

var closureCompiler = require('google-closure-compiler').gulp();
var flatmap = require('gulp-flatmap');    
var watch = require('gulp-watch');

gulp.task('js-closure', function () {
    return watch(['app/js/*.js', 'dist/single.js'], function()
    {
        gulp.src(['app/js/*.js', 'dist/single.js'], {base: './'})
            .pipe(flatmap(function(stream, file) {
                return stream.pipe(closureCompiler({
                    compilation_level: 'SIMPLE_OPTIMIZATIONS',
                    warning_level: 'QUIET',
                    language_in: 'ECMASCRIPT6_STRICT',
                    language_out: 'ECMASCRIPT5_STRICT',
                    output_wrapper: '(function(){\n%output%\n}).call(this)',
                    js_output_file: path.basename(file.path).replace(/js$/, 'min.js')
                }))
            }))
            .pipe(gulp.dest('./dist/js'));
    });
});
guagay_wk
  • 26,337
  • 54
  • 186
  • 295