Search code examples
javascriptgulpgoogle-closure-compilergoogle-closure

Using gulp with google closure to compile js files into individual files instead of a single file


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

I have the 3 js files in app/js folder. They are controller.js, app.js, services.js.

Here is my gulpfile code:

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

gulp.task('js-closure', function () {
    return gulp.src('app/js/*.js', {base: './'})
        .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: 'output.min.js'
        }))
        .pipe(gulp.dest('./dist/js'));
});

What the code does is compile the 3 js files into a single file output.min.js

What I want is to compile the 3 js files into 3 separate js files controller.min.js, app.min.js, services.min.js


Solution

  • As far as I can see there's no way to avoid having your files combined by the Google Closure Compiler. Even if you leave out the js_output_file option it will simply default to the output file name compiled.js. That means you have to invoke the Closure Compiler for each file.

    The gulp-flatmap plugin lets you do that easily. You just have to determine the value of js_output_file for each input file (basically replace .js with .min.js in each file name):

    var flatmap = require('gulp-flatmap');
    var path = require('path');
    
    gulp.task('js-closure', function () {
      return gulp.src('app/js/*.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'));
    });