AngularJS 缩小的 js 文件不起作用

AngularJS minified js files not working

我将所有 js 文件缩小并合并为一个文件并包含在 html 站点中没有任何内容。

js文件太多,不想一一包含,修改合并成一个。

有没有其他方法可以减少 js 文件的 http 调用次数。

缩小您的 AngularJS 文档时,请务必按照文档进行依赖注入,否则您的代码可能会中断。您应该确保您使用的是首选数组方法,示例如下:

   someModule.controller('MyController', ['$scope', 'greeter', function($scope, greeter) {
  // ...
}]);

如官方 Angular JS 文档所示:https://docs.angularjs.org/guide/di.

跟进@dayle-salmon 的回答,如果你有这样的控制器

app.controller('DemoCtrl', function(dependency1, dependency2){
 // controller code
});

改为

app.controller('DemoCtrl', ['dependency1', 'dependency2', function(dependency1, dependency2){
 // controller code
}]);

原因 JS 压缩器通常会更改注入的依赖项的名称。 Angular 不知道依赖项是什么。所以,你手动声明它们,这样缩小后就不会出现问题了!

看来,这是implicit dependency injection的一个原因。根据 Angular JS 文档:

Careful: If you plan to minify your code, your service names will get renamed and break your app.

改用strict dependency injection。例如:

angular
  .module("MyModule")
  .controller("MyCtrl", ["$scope", "$timeout", function ($scope, $timeout) {
    ...
  }]);

此外,考虑使用 ng-annotate 这更容易:

angular
  .module("MyModule")
  .controller("MyCtrl", function ($scope, $timeout) {
    "ngInject";
    ...
  });