使用gulp压缩合并AngularJS项目中js

AngularJS项目中js众多,上线的时候压缩合并下还是很有必要的^_^

在此之前如果不了解gulp,推荐访问Gulp开发教程(翻译)

值得注意的是,一般书写时按照简写的格式:

angular.module("MyMod").controller("MyCtrl", function($scope, $timeout) {  
});

但是压缩js会破快AngularJS文件所需的依赖注入,以至于无法工作,因此压缩前你需要将代码手动修改为下面的形式:

angular.module("MyMod").controller("MyCtrl", ["$scope", "$timeout", function($scope, $timeout) {  
}]);

在此着重介绍下ng-annotate这个项目,它会自动帮你做这件事$_$,这个项目正好提供了gulp的插件,因此顺理成章:

var gulp = require('gulp');  
var ngAnnotate = require('gulp-ng-annotate');  
var gutil = require('gulp-util');  
var bower = require('bower');  
var uglify = require('gulp-uglify');  
var concat = require('gulp-concat');  
var minifyCss = require('gulp-minify-css');  
var rename = require('gulp-rename');  
var sh = require('shelljs');  
var ngmin = require('gulp-ngmin');  
var stripDebug = require('gulp-strip-debug');  

gulp.task('minify', function() {  
    return gulp.src(['js/appService.js','js/app.js']) //注意,此处特意如此,避免顺序导致的问题
        .pipe(ngAnnotate())
        .pipe(ngmin({dynamic: false}))  
        .pipe(stripDebug())  
        .pipe(uglify({outSourceMap: false}))  
        .pipe(concat('all.min.js'))  
        .pipe(gulp.dest('js/'))  
});   

小刀

Read more posts by this author.

Subscribe to cc log

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!
comments powered by Disqus