How to minify project in angularjs?

5

When I do the minification in the angular everything stops working

    
asked by anonymous 26.03.2017 / 17:18

2 answers

6

The problem is that the minification process changes the name of the parameters of the functions. There is no problem with 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 the Angular after the minification, since the parameters of the functions will be replaced by other random and minor names that have nothing to do.

To solve this problem, Angular has the annotation system, an annotation system that lets you say what should be injected into each controller parameter, even if its name is changed.

Example:

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

Turns:

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

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

    
26.03.2017 / 17:25
5

As previously stated, the build process renames the function declarations, 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 some task runner as Grunt , Gulp or Webpack ng-annotate resolves your life.

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

Here's the documentation: link and here the tutorials to use with task runners : link

    
26.03.2017 / 17:52