如何正确缩小 angularJS 文件

How to correctly minify angularJS file

我有一个简单的 angularjs 指令,当我缩小文件时出现错误,因为变量名称已更改

var app= angular.module('app',[]);

app.directive('directive',function(){
    return {
        restrict: 'EA',
        scope: {},
        replace: true,
        link: function($scope, element, attributes){
            $scope.name="test-test";
        ,
        controller: function($scope,$attrs,$http){

        },
        templateUrl: 'directives/app/app.tpl.html'
    }
});

问题是 $scope.name 变成了 a.name 而 angular 无法识别它。 我尝试通过

之类的方式注入 $scope
link: ['$scope',function($scope, element, attributes){
            $scope.name="test-test";
}],
controller: ['$scope','$attrs','$http',function($scope,$attrs,$http){

}],

但缩小后我仍然得到 a.name 相同的错误。

link 函数未进行依赖注入。它仅使用位置参数,因此您不必使用显式数组命名。我觉得控制器一个很好。

最后,请记住,您必须为了清晰起见而编写代码。显式语法有点过于冗长,这就是大多数人选择使用 ng-annotate 的原因。 Ng-annotate 是一个编译步骤,它将在缩小之前将代码转换为显式形式。

指令link 函数未注入。他们传递了一组固定的参数,这些参数在 angular.js documentation 中列出并进行了全面描述。然而,controller 并非如此。这些是注入的,应该在缩小之前进行注释。您至少可以通过 3 种方式完成:

  • 像您的示例一样使用数组语法
  • 在控制器功能上设置$inject 属性,值为注射剂名称数组
  • 使用 ngAnnotate 注释,这将检测 angular 注入的使用并正确注释它