Use Closure Compiler with AngularJS in ADVANCED_MO

2019-05-18 10:12发布

问题:

I'm trying to compile one of our angular & openLayers project but I'm not able to use Angular.

I've put the angular external parameter, but after compiling i get this error :

Error: [$injector:unpr] Unknown provider: aProvider <- a <- myCtrl
http://errors.angularjs.org/1.3.15/$injector/unpr?p0=aProvider%20%3C-%20a%20%3C-%20myCtrl
    at REGEX_STRING_REGEXP (angular.js:63)
    at angular.js:4015
    at Object.getService [as get] (angular.js:4162)
    at angular.js:4020
    at getService (angular.js:4162)
    at Object.invoke (angular.js:4194)
    at $get.extend.instance (angular.js:8493)
    at angular.js:7739
    at forEach (angular.js:331)
    at nodeLinkFn (angular.js:7738)

Here's a simple example to illustrate my problem:

html:

<div ng-app="myApp" ng-controller="myCtrl">
  First Name: <input type="text" ng-model="firstName"><br>
  Last Name: <input type="text" ng-model="lastName"><br>
  <br>
  Full Name: {{firstName + " " + lastName}}
</div>

<script src="angular/angular.js"></script>
<script src="vmap.js"></script>

script:

  goog.provide("vmap");

vmap = function(){

};


var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName= "John";
    $scope.lastName= "Doe";
});

To compile the files, I use the command below :

python closure-library/closure/bin/build/closurebuilder.py
--root=closure-library/ 
--root=../debug/ 
--namespace="vmap" 
--output_mode=compiled 
--compiler_jar=compiler.jar 
--compiler_flags="
    --compilation_level=ADVANCED_OPTIMIZATIONS" 
    --compiler_flags="--externs=../debug/lib/angular/angular-1.3.js" 
    --compiler_flags="--angular_pass" > ../vmap.js

I've found the angular-1.3.js file here

What did I miss ?

回答1:

  1. Add @ngInject in jsdocs of the controller constructor function,
  2. Pass in the function as an argument to angular module app.controller('myCtrl', fn)
  3. Make sure to pass in --angular_pass argument to the closure compiler.

So, here is a modified version of the provided example that should work for you:

goog.provide("vmap");

/**
 * @constructor
 * @ngInject
 */
vmap = function($scope) {
    $scope.firstName= "John";
    $scope.lastName= "Doe";
};


var app = angular.module('myApp', []);
app.controller('myCtrl', vmap);


回答2:

Write you controller using the array notation:

app.controller('myCtrl', ['$scope', function($scope) {
    $scope['firstName'] = "John";
    $scope['lastName'] = "Doe";
}]);

As local variables (like $scope) get renamed, and object properties ($scope.firstName) too, unless you write them using the string notation.

More information about minification in AngularJS here: https://docs.angularjs.org/tutorial/step_05#a-note-on-minification