2013-03-29 92 views
8

我對使用編譯器工具自動化/簡化角度項目感興趣,它可能適用於其他任何工作,但角度注入和命名空間足夠尷尬以逃避編譯器知識。做這件事的最佳/專業方法是什麼?縮小角度

感謝,最後一兩件事,

app.controller('ctrl',['$rootScope',function($rootScope){ 
    ... 
}]); 

作品時精縮,但我怎麼再壓縮

app.config(['$routeProvider', function($routeProvider){ 

}]); 

,當我再壓縮的連續動作操作呢?

app.controller(...).directive(...).run(...) 
+0

這些都應該做工精細。看看我的構建腳本:http://github.com/joshdmiller/ng-boilerplate。但我不確定你在這裏具體問的是什麼。你遇到什麼問題? –

+0

app.config(['$ routeProvider',function($ routeProvider){$ routeProvider.something()...}]);在縮小時變成app.config(['$ routeProvider',function(e){ef = function()...),並導致e-> eProvider錯誤。 $ injector or $ inject在應用程序的某處? – user2167582

+0

您提供的代碼對我來說工作得很好 - 再次檢查一下這個鏈接。你能發佈函數的主體嗎? –

回答

11

在Angular中,您需要註釋注入器的函數以知道要在函數中注入哪些依賴關係。基本上有三種方法在您的函數中注入依賴關係,正在官方角色網站上描述。這三種方法是:

1.使用內嵌陣列註釋

yourModule.controller('yourController', ['$scope', function($scope) {}]); 

2.使用$從功能注入性註釋

var yourController = function($scope) {}; 

yourController.$inject = ['$scope']; 

yourModule.controller('yourController', yourController); 

3.Implictly參數名稱

yourModule.controller('yourController', function($scope) {}); 

現在,當您縮小項目時,您的依賴項名稱將被重命名。 在第一種情況下你的代碼會像

yourModule.controller('yourController', ['$scope', function(e) {}]); 

在第三種情況下你的代碼會像

yourModule.controller('yourController', function(e) {}); 

它會破壞你的應用程序,因爲角沒有辦法認出你的依賴的名字。所以建議不要在你的項目中使用隱式依賴注入。從上面的兩個內聯數組註釋是程序員中最流行的方式。

2

我會推薦使用https://github.com/olov/ng-annotate。它可以讓你編寫你的代碼如下。

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

然後ngAnnotate把它變成下面這個對於縮小是安全的。

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

minifyer不改變字符串,這就是爲什麼我們使用數組符號。鏈接方法不會改變minifyer保持字符串完整的方式。

var app=module(myapp); 
app.config(['$routeProvider', function($routeProvider){ 
$routeProvider.dosomestuffs() 
}]); 

將在東西被精縮樣

var a=module(myapp); 
a.config(['$routeProvider', function(b){ 
     b.dosomestuffs() 
}]); 

但角度仍然會發現其歸功於「$ routeProvider」串繞的方式。

0

如果您總是使用註釋,那麼不應該存在縮小角度腳本的問題。

app.controller(['$scope', function(mrScope) { 
    mrScope.yourProperty = 'it does not matter the dependency variable names if you use annotations'; 
}]); 
0

只要您使用數組符號表示要注入的依賴關係,就不會出現縮小問題。您正在使用的縮小工具應該可以毫無問題地處理您的任何示例(在我的項目中,我們使用uglify來完成該工作)。實際上,對於奇怪名稱的注入(以點和字符命名,導致無效的函數名稱,如ABC.CDE),數組表示法是注入它們的最佳方法。

0

我在縮小時遇到了同樣的問題,和你一樣,只有$routeProvider配置元素失敗。對我來說,答案是使用像Himanshu所說的$inject方法來配置我的配置,即使你顯示的語法你的第一個例子適用於我的控制器。所以,我會在這裏發佈我.config()代碼,因爲我沒有看到它在上面的答案明確列出:

var app = angular.module('myApp'); 
var RouteProviderConfig = function ($routeProvider) { 
     $routeProvider 
      .when(...) 
      .otherwise(...); 
    }; 
RouteProviderConfig.$inject = ['$routeProvider']; 
app.config(RouteProviderConfig); 

這個固定我的錯誤CONFIGS,但我的工作的控制器你的第一個例子是編寫方式:

app.controller('ctrl',['$rootScope',function($rootScope){ 
    ... 
}]); 

Angular Documentation似乎表明,這兩種方式應該工作,所以我認爲這是可能有一個bug與CONFIGS,或$routeProvider,或別的東西完全...