指令碼優化

將 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']);
};