GulpJS: Minifying Files

Standard

Minifying Files

  • Use gulp-Uglify to remove whitespace, comments, minify javascript files
  • Use gulp-CSSO to remove whitespace, comments, transform css files
  • Use gulp-filter to seperate out/reduce/filter files from gulp stream
  • Manglin your code can break angular dependency injection, in order to avoid this use Strict Dependency Injection (ng-strict-di) or $inject Property Annotation
  • Filter.restore() function put filter back into stream

Pre Install:

    npm install --save-dev gulp gulp-load-plugins 

Install:

    npm install --save-dev gulp-filter@v2.0.0 gulp-csso gulp-uglify

Code:

    var gulp = require('gulp');
    var $ = require('gulp-load-plugins')({ lazy: true });
    var assets = $.useref.assets({ searchPath:  './' });
    var cssFilter = $.filter('**/*.css');
    var jsFilter = $.filter('**/*.js');

    gulp.task('minify', function () {

        return gulp
            .src('./build/index.html')
            .pipe(assets)
            .pipe(cssFilter)
            .pipe($.csso())
            .pipe(cssFilter.restore())
            .pipe(jsFilter)
            .pipe($.uglify())
            .pipe(jsFilter.restore())
            .pipe(assets.restore())
            .pipe($.useref())
            .pipe(gulp.dest('./build/'));
    });

Execute:

    gulp minify 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s