[英]Angularjs minification using grunt uglify resulting in js error
在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');
})
它的缩小版本无法通过角度正确解释。
由于我们必须开始项目开发活动,我们无法花足够的时间来研究问题,我们开始使用控制器而不缩小它们。 所以第一个问题是角度是否存在这样的问题,或者我犯了一些错误,并且由于它不起作用? 如果存在这样的问题,它的解决方案是什么?
您必须使用基于字符串注入的语法,以确保缩小版本指向良好的依赖性:
function checkInCtrl ($scope, $rootScope, $location, $http){}
成为:
['$scope', '$rootScope', '$location', '$http', function checkInCtrl ($scope, $rootScope, $location, $http){}]
有关信息,ngMin已被弃用 。 您应该使用ngAnnotate ,而不是与精美的作品咕噜和一饮而尽 。
纳瓦迪普,
来自Bixi的建议解决方案将起作用。 然而,更简单的方法就是使用ngmin Grunt插件。 使用这个插件,你不需要像你所做的那样处理依赖注入,也不需要像Bixi这样的特殊语法。
要使用它,请确保你有grunt-ngmin
并在grunt-ngmin
之前调用它。
你的Gruntfile.js:
ngmin: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: '*.js',
dest: '.tmp/concat/scripts'
}]
}
},
....
grunt.registerTask('build', [
'ngmin',
'uglify',
]);
获得uglify和minify工作将揭示(就像我的情况一样)注入变量从$ scope变为'a'的地方示例:此代码:
controller: function($scope) {
$scope.showValidation= false;
this.showValidation = function(){
$scope.showValidation = true;
};
}
缩小后,uglify变为:
controller:function(a){a.showValidation=!1,this.showValidation=function(){a.showValidation=!0}}
而且你得到一个错误,因为'a'与$ scope不同。
解决方案是显式声明注入的变量:
controller: ['$scope', function($scope) {
$scope.showValidation= false;
this.showValidation = function(){
$scope.showValidation = true;
};
}]
缩小后,uglify变为:
controller:["$scope",function(a){a.showValidation=!1,this.showValidation=function(){a.showValidation=!0}}]
现在'a'映射到$ scope。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.