Angularjs minification using grunt uglify resulting in js error

点点圈 提交于 2019-11-27 05:03:48

You have to use the string-injection based syntax that ensure that the minified version points to the good dependancy :

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

becomes :

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

For info, ngMin has been deprecated. You should use ngAnnotate instead which works beautifully with grunt and gulp.

suriyanto

Navdeep,

The suggested solution from Bixi will work. However the easier way is just to use ngmin Grunt plugin. Using this plugin, you don't need to handle the dependency injection like what you did and also no need for the special syntax like Bixi.

To use it, make sure you have grunt-ngmin and that you call it before uglify.

Your Gruntfile.js:

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

....

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

Getting uglify and minify to work will reveal (as it did in my case) places where injected variables are changed from something like $scope to 'a' Example: This code:

controller: function($scope) {
        $scope.showValidation= false;
        this.showValidation = function(){
            $scope.showValidation = true;
        };
    }

after minify and uglify becomes:

controller:function(a){a.showValidation=!1,this.showValidation=function(){a.showValidation=!0}}

And you get an error because 'a' is not the same as $scope.

Solution is to explicitly declare the injected variables:

controller: ['$scope', function($scope) {
        $scope.showValidation= false;
        this.showValidation = function(){
            $scope.showValidation = true;
        };
    }]

after minify and uglify becomes:

controller:["$scope",function(a){a.showValidation=!1,this.showValidation=function(){a.showValidation=!0}}]

Now 'a' is mapped to $scope.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!