Angularjs 缩小最佳实践

IT技术 javascript angularjs dependency-injection
2021-01-31 22:04:47

我正在阅读 http://www.alexrothenberg.com/2013/02/11/the-magic-behind-angularjs-dependency-injection.html事实证明,如果您缩小 javascript,angularjs 依赖注入会出现问题,所以我我想知道如果不是

var MyController = function($scope, $http) {
    $http.get('https://api.github.com/repos/angular/angular.js/commits')
      .then(function(response) {
        $scope.commits = response.data
      })
  }

你应该使用

var MyController = ['$scope', '$http', function($scope, $http) {
  $http.get('https://api.github.com/repos/angular/angular.js/commits')
    .then(function(response) {
      $scope.commits = response.data
    })
}]

总而言之,我认为第二个片段是针对旧版本的 angularjs 但是....

我应该总是使用注入方式(第二种)吗?

6个回答

是的,永远!因此,即使您的 minifer 将 $scope 转换为变量 a 并将 $http 转换为变量 b,它们的身份仍然保留在字符串中。

查看AngularJS 文档的这个页面,向下滚动到A Note on Minification

更新

或者,您可以在构建过程中使用ng-annotate npm 包来避免这种冗长。

这个以及其他一些问题在egghead.io 上有很好的解释。JFYI
2021-03-31 22:04:47
2021-04-02 22:04:47
关于缩小的说明已移至此处docs.angularjs.org/tutorial/step_07
2021-04-04 22:04:47
您可以在运行缩小之前使用 ngmin 和构建工具(如 Grunt),而不是使用这种更冗长的语法。这样你就可以正确缩小,但也可以使用依赖注入语法。
2021-04-06 22:04:47
@Sprotenwels:是的!那里有很多有用的资源。
2021-04-08 22:04:47

使用第二个变体更安全,但也可以通过ngmin安全地使用第一个变体

更新:
现在ng-annotate成为解决此问题的新默认工具。

是的,您需要使用显式依赖注入(第二个变体)。但是从Angular 1.3.1 开始,你可以关闭隐式依赖注入,这对于解决一次重命名的潜在问题(在缩小之前)非常有帮助。

使用strictDi配置属性关闭隐式 DI

angular.bootstrap(document, ['myApp'], {
    strictDi: true
});

关闭隐式 DI,使用ng-strict-di指令:

<html ng-app="myApp" ng-strict-di>

只是要指出,如果你使用

约曼

没有必要像

var MyController = ['$scope', '$http', function($scope, $http) {
  $http.get('https://api.github.com/repos/angular/angular.js/commits')
    .then(function(response) {
      $scope.commits = response.data
    })
}]

因为缩小期间的咕噜声考虑了如何管理 DI。

就像 OZ_ 说的,使用 ngmin 来缩小所有 angular js 文件,比如directive.js service.js。之后,您可以使用 Closure 编译器对其进行优化。

参考:

如何缩小 angularjs 脚本

与 YO 一起构建