使用grunt uglify进行Angularjs缩小导致js错误

时间:2014-04-04 14:56:12

标签: javascript angularjs dependency-injection gruntjs uglifyjs

在angularjs中,我们将参数作为依赖注入传递。例如,

function checkInCtrl ($scope, $rootScope, $location, $http){
…..
….
}

因此,当它变得微小时,就会变得像,

function checkInCtrl(a,b,c,d){
}

现在a,b,c,d将不会被解释为$ scope,$ rootScope,$ location,$ http分别由angular和整个代码无法工作。为此,angularjs提供了一个解决方案,即

checkInCtrl.$inject = ['$scope', '$rootScope', $location', '$http'];

我们可以使用上面的语法注入不同的依赖项。这很好用,直到我没有使用一些自定义角度服务作为依赖。例如,

如果我有类似

的话
function checkInCtrl ($scope, $rootScope, $location, $http){
…..
….
}

它适用于给定的解决方案,但如果我有类似

的东西
function checkInCtrl ($scope, $rootScope, $location, $http, customService){
…..
….
}

其中customService类似于

angular.module(customService, ['ngResource'])
                .factory('abc', function($resource) {
                                return $resource('/abc');
                })

它的缩小版本无法通过角度正确解释。

由于我们必须开始项目开发活动,我们无法花费足够的时间来研究问题,我们开始使用控制器而不缩小它们。所以第一个问题是角度是否存在这样的问题,或者我犯了一些错误,并且由于它不起作用?如果存在这样的问题,它的解决方案是什么?

3 个答案:

答案 0 :(得分:27)

您必须使用基于字符串注入的语法,以确保缩小版本指向良好的依赖性:

function checkInCtrl ($scope, $rootScope, $location, $http){}

成为:

['$scope', '$rootScope', '$location', '$http', function checkInCtrl ($scope, $rootScope, $location, $http){}]

答案 1 :(得分:9)

有关信息,ngMin已deprecated。您应该使用ngAnnotate而不是gruntgulp

答案 2 :(得分:7)

纳瓦迪普,

Bixi建议的解决方案可行。然而,更简单的方法就是使用ngmin Grunt插件。使用这个插件,你不需要像你做的那样处理依赖注入,也不需要像Bixi这样的特殊语法。

要使用它,请确保您拥有grunt-ngmin并在uglify之前调用它。

你的Gruntfile.js:

ngmin: {
  dist: {
    files: [{
      expand: true,
      cwd: '.tmp/concat/scripts',
      src: '*.js',
      dest: '.tmp/concat/scripts'
    }]
  }
},

....

grunt.registerTask('build', [
  'ngmin',
  'uglify',
]);