【问题标题】:Minifying and Bundling AngularJS in Visual Studio在 Visual Studio 中缩小和捆绑 AngularJS
【发布时间】:2014-12-04 06:34:13
【问题描述】:

我正在尝试在 Visual Studio 2013 中缩小和捆绑我的 AngularJS/WebAPI 项目。当我在缩小后运行我的项目时,出现如下错误:

Error: [$injector:modulerr] http://errors.angularjs.org/1.2.13/$injector/modulerr?p0=app&p1=%5B%24injector%3Aunpr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.2.13%2F%24injector%2Funpr%3Fp0%3Dn%0Av%2F%3C%40http%3A%2F%2Flocalhost%3A63389%2Fbundles%2Fangular%3Fv%3D_ykkA4necF0i5wrX1pYwFxAqwK5bvRGCF4SEL-Meqac1%3A1%0Ane%2Fu.%24injector%3C%40http%3A%2F

从我所做的阅读看来,Angular 在压缩代码后遇到了注入问题。我试图弄清楚是否有“最佳实践/工作流程”可以在 Visual Studio 中进行调试。如何理解上述错误?

【问题讨论】:

标签: visual-studio angularjs asp.net-web-api visual-studio-2013 angularjs-scope


【解决方案1】:

我在缩小 AngularJs 应用程序时看到的唯一问题是函数参数注入语法。喜欢:

app.config(function($serviceA, $serviceB) { ... });

缩小时,函数参数可能会更改为更短的名称。所以这可能变成:

app.config(function(a, b) { ... });

这是未知的。您应该始终使用数组注入语法(我还没有看到不好的情况..):

app.config(['$serviceA', '$serviceB', function($serviceA, $serviceB) { ... }]);

函数参数将被缩小,但字符串常量不会,这使 Angular 可以知道您所询问的服务的名称,而不管函数参数名称是什么。

【讨论】:

    【解决方案2】:

    我了解到最好的解决方案不是使用 ASP.NET MVC 缩小,而是使用 Gruntng-annotate。这将装饰 AngularJS 控制器并缩小它们。学习需要一点时间,但值得。如果您觉得有用,我可以提供一个 Grunt 脚本示例。

    【讨论】:

      【解决方案3】:

      您需要在 Visual Studio 缩小更改 $scope 和其他变量时注释您的代码。

      改变

      var MyController = function($scope, $http) { ..  }
      

      var MyController = ['$scope', '$http', function($scope, $http) { .. }]
      

      参考资料: http://weblogs.asp.net/dwahlin/structuring-angularjs-codeAngularjs minify best practice

      【讨论】:

      • 在数组注入语法未被广泛使用的自定义指令中,您也会遇到此问题。
      【解决方案4】:

      Angular 文档对此有一个note...

      由于 Angular 从参数名称推断控制器的依赖关系到控制器的构造函数,如果你要缩小 PhoneListCtrl 控制器的 JavaScript 代码,它的所有函数参数也会被缩小,并且依赖注入器不会能够正确识别服务。

      例子:

      var phonecatApp = angular.module('phonecatApp', []);
      
      phonecatApp.controller('PhoneListCtrl', ['$scope', '$http',
        function ($scope, $http) {
          $http.get('phones/phones.json').success(function(data) {
            $scope.phones = data;
          });
      
          $scope.orderProp = 'age';
        }]);
      

      【讨论】:

        猜你喜欢
        • 2017-12-13
        • 2012-08-15
        • 2016-12-25
        • 2013-02-01
        • 2016-09-27
        • 2016-12-13
        • 2014-11-26
        • 2013-06-27
        • 2012-06-28
        相关资源
        最近更新 更多