How to minify project in Angularjs?

Asked

Viewed 582 times

5

When I do the minification at the angle everything stops working

  • Related: http://answall.com/questions/184816/inje%C3%A7%C3%A3o-de-depend%C3%Aancia/184851#184851

2 answers

6


The problem is that the minification process changes the name of the function parameters. There is no problem in this, as long as the new name is changed everywhere it is used, but the Angular dependency injection system is based on the name of the parameters. The conclusion of this is that nothing else will work in Angular after minification, since the function parameters will be replaced by other random and smaller names that have nothing to do.

To solve this problem, Angular has the Annotation system, an annotation system that allows you to tell what should be injected for each controller parameter, even if its name is changed.

Example:

angular.module('qualquer')
    .controller('QualquerController', function($scope, $routeParams) {
            // seu código 
    });

Vira:

angular.module('qualquer')
    .controller('QualquerController', [$scope, $routeParams] {
            //  seu código 
    });

Note that the second parameter of the controller is an array that first receives all the artifacts that the Angular controller will receive and finally the function that defines the controller. The minification process will never touch the array data and Angular follows the convention that the first parameter of the array will be injected as the first parameter of the controller function. If the controller function parameter name changes, everything will continue to work.

5

As answered earlier, the build process renames the function statements, but preserves the array with the name that should match the dependency injection.

I’m not sure how you’re doing the minification process, but if you’re using any task runner as Grunt, Gulp or Webpack the ng-annotate solves your life.

It preserves the name of the imported dependencies in the build process.

Here is the documentation: https://github.com/olov/ng-annotate and here the tutorials to use with task runners: https://github.com/olov/ng-annotate#tools-support

  • 1

    +1 for the reference to ng-annotate. The question is focused on the minification process, not on changing the content of the project.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.