脚本优化

将 JS 文件组合在一起并缩小它们是一种很好的做法。对于较大的项目,可能有数百个 JS 文件,并且它会增加不必要的延迟,以便从服务器单独加载每个文件。

对于角度缩小,需要对所有功能进行注释。这对于 Angular 依赖注入适当的 minificaiton 是必要的。 (在缩小期间,函数名称和变量将被重命名,如果不采取额外的操作,它将破坏依赖注入。)

在 minificaiton $scopemyService 变量将被其他一些值替换。角度依赖注入基于名称工作,因此,这些名称不应更改

.controller('myController', function($scope, myService){
})

Angular 将理解数组表示法,因为缩小不会替换字符串文字。

.controller('myController', ['$scope','myService', function($scope, myService){
}])
  • 首先,我们将端到端地汇总所有文件。
  • 其次我们将使用 ng-annotate 模块,它将准备缩小代码
  • 最后我们将应用 uglify 模块。

module.exports = function(grunt){//在这里设置脚本的位置,以便在代码中重用它脚本位置= [‘app / scripts / * .js’];

 grunt.initConfig({
        pkg: require('./package.json'),
            //add necessary annotations for safe minification
         ngAnnotate: {
            angular: {
                src: ['staging/concatenated.js'],
                dest: 'staging/anotated.js'
            }
        },
        //combines all the files into one file
        concat: {
                js: {
                    src: scriptLocation,
                    dest: 'staging/concatenated.js'
                }
            },
        //final uglifying
        uglify: {
            options: {
                report: 'min',
                mangle: false,
                sourceMap:true
            },
            my_target: {
                files: {
                    'build/app.min.js': ['staging/anotated.js']
                }
            }
        },
        
        //this section is watching for changes in JS files, and if there was a change, it will regenerate the production file. You can choose not to do it, but I like to keep concatenated version up to date
        watch: {
            scripts: {
                files: scriptLocation,
                tasks: ['buildJS']
            }
        }
            
});

    //module to make files less readable
    grunt.loadNpmTasks('grunt-contrib-uglify');
    
    //mdule to concatenate files together
    grunt.loadNpmTasks('grunt-contrib-concat');
    
    //module to make angularJS files ready for minification
    grunt.loadNpmTasks('grunt-ng-annotate');
    
    //to watch for changes and if the file has been changed, regenerate the file
    grunt.loadNpmTasks('grunt-contrib-watch');
    
    //task that sequentially executes all steps to prepare JS file for production
    //concatinate all JS files
    //annotate JS file (prepare for minification
    //uglify file
     grunt.registerTask('buildJS', ['concat:js', 'ngAnnotate', 'uglify']);
};