使用 grunt uglify 进行 Angularjs 缩小导致 js 错误 [英] Angularjs minification using grunt uglify resulting in js error

查看:23
本文介绍了使用 grunt uglify 进行 Angularjs 缩小导致 js 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In angularjs we pass parameters as dependency injection. For example,

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

所以当它被缩小时,它变得像,

So when it gets minified, it becomes like,

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

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

Now a,b,c,d won’t be interpreted as $scope, $rootScope, $location, $http respectively by angular and whole code fails to work. For this angularjs has provided one solution, which is

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

我们可以使用上述语法注入不同的依赖项.这很有效,直到我没有使用某些自定义 Angular 服务作为依赖项.例如,

we can inject different dependencies by using above syntax. This worked well till I didn’t use some custom angular service as dependency. So for example ,

如果我有类似的东西

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

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

It works with given solution, but if I have something like

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

customService 类似于

Where customService is something like

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

它的缩小版本没有被 angular 正确解释.

It’s minified version doesn’t get interpreted properly by angular.

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

As we had to start project development activities, we couldn’t spend enough time to look into matter and we started using controller without minifying them. So first question is whether there is such problem with angular or I made some mistake and due to which it didn't work? If such issue exist,what is solution to it?

推荐答案

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

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){}

变成:

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

这篇关于使用 grunt uglify 进行 Angularjs 缩小导致 js 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆