簡體   English   中英

Grunt 構建導致 Angular 應用程序在 dist 上崩潰

[英]Grunt build causing Angular app to crash on dist

我正在使用 Grunt 並執行 cmd“grunt build”來創建一個包含 AngularJS 應用程序的分發文件夾。

作為一個獨立的我的應用程序運行良好。 一旦我為應用程序創建了一個發行版,應用程序就會很快崩潰。

我在 F12 工具控制台中看到的是:

已達到 10 次 $digest() 迭代。 中止!

我懷疑我的 .tmp 目錄中有一個名為 vendor.js 的文件,並且由於控制器依賴注入變量將注入的控制器參數(如“$scope”到“a”)進行了重整,因此無法正確縮小、丑化和/或連接該文件,例如,即使我正在使用 ngAnnotate。

請參閱我正在使用 UglifyJs 並在 Uglify 和 Concat 之前調用 ngAnnotate 但我無法從 useMinPrepare 中刪除 UglifyJs 或者我有其他錯誤,例如腳本目錄甚至沒有在我的 dist 目錄中創建:

useminPrepare: {
  html: '<%= yeoman.app %>/index.html',
  options: {
    dest: '<%= yeoman.dist %>',
    flow: {
      html: {
        steps: {
          js: ['concat', 'uglifyjs'],
          css: ['cssmin']
        },
        post: {}
      }
    }
  }
},

我在 GruntJs 文件中設置 mangle = false 但我懷疑 useMinPrepare js: ['concat', 'uglifyjs']在調用useMin時更改執行順序並在 ngAnnotate 可以運行之前運行useMin ,即使我在調用useMin之后ngAnnotate

我是 Grunt 的新手,這個應用程序是從另一個開發人員那里傳給我的。

我發現這篇文章對我來說並不完全有意義,也不是似乎適用於我的 Gruntfile.js 的代碼更改,但我想也許我正在做一些事情:

https://github.com/DaftMonk/generator-angular-fullstack/issues/164

我已將 Uglify mangle 選項設置為 false,但它並沒有解決我的問題。

這是我的 Gruntfile.js 代碼:

  module.exports = function (grunt) {

    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    // Time how long tasks take. Can help when optimizing build times
    require('time-grunt')(grunt);

    grunt.loadNpmTasks('grunt-connect-proxy');

    // Define the configuration for all the tasks
    grunt.initConfig({

    // Project settings
    yeoman: {
      // configurable paths
      app: require('./bower.json').appPath || 'app',
      dist: 'dist'
    },

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['bowerInstall']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/**/*.js'],
      //        tasks: ['newer:jshint:all'],
        options: {
          livereload: true
        }
      },
      html: {
            files: ['**/*.html'],
            options: {
                livereload: true
            }
        },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: '0.0.0.0',
        //hostname: 'localhost',
        livereload: 35729
      },
      proxies: [{
        context: ['/api', '/images'],
        host: '127.0.0.1',
        port: 60878,
        changeOrigin: true
      }],
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '<%= yeoman.app %>'
          ],
          middleware: function (connect, options) {
            var middlewares = [];

            if (!Array.isArray(options.base)) {
              options.base = [options.base];
            }

            // Setup the proxy
            middlewares.push(require('grunt-connect-proxy/lib/utils').proxyRequest);

            // setup push state
            middlewares.push(require('grunt-connect-pushstate/lib/utils').pushState());


            // Serve static files
            options.base.forEach(function(base) {
              middlewares.push(connect.static(base));
            });

            return middlewares;
          }
        }
      },
      test: {
        options: {
          port: 9001,
          base: [
            '.tmp',
            'test',
            '<%= yeoman.app %>'
          ]
        }
      },
      dist: {
        options: {
          base: '<%= yeoman.dist %>',
          middleware: function (connect, options) {
            var middlewares = [];

            if (!Array.isArray(options.base)) {
              options.base = [options.base];
            }

            // Setup the proxy
            middlewares.push(require('grunt-connect-proxy/lib/utils').proxyRequest);

            // setup push state
            middlewares.push(require('grunt-connect-pushstate/lib/utils').pushState());

            // Serve static files
            options.base.forEach(function(base) {
              middlewares.push(connect.static(base));
            });

            return middlewares;
          }
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'Gruntfile.js',
        '<%= yeoman.app %>/scripts/{,*/}*.js'
      ],
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/*',
            '!<%= yeoman.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    bowerInstall: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath: '<%= yeoman.app %>/'
    //        ,exclude : ["bower_components/angular-snap/angular-snap.css"]
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: '<%= yeoman.app %>/bower_components/'
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: '<%= yeoman.app %>/bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false,
        raw: 'Sass::Script::Number.precision = 10\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated',
          fontsDir: '<%= yeoman.dist %>/styles/fonts'
        }
      },
      server: {
        options: {
          debugInfo: false
        }
      }
    },

    // Renames files for browser caching purposes
    rev: {
      dist: {
        files: {
          src: [
            '<%= yeoman.dist %>/scripts/{,*/}*.js',
            '<%= yeoman.dist %>/styles/{,*/}*.css',
            '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
    //            ,'<%= yeoman.dist %>/styles/fonts/*'
          ]
        }
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
               js: ['concat', 'uglifyjs'], 
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    uglify: {
        dist: {
           options : {
            report: 'min',
            mangle : false
           // compress: false,
           // beautify : true
        }
    }
  },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>', '<%= yeoman.dist %>/styles/fonts', '<%= yeoman.dist %>/images' ]
      }
    },

    concat: {
      options: {
        separator: grunt.util.linefeed + ";" + grunt.util.linefeed
      }
    },

    // The following *-min tasks produce minified files in the dist folder
    //    cssmin: {
    //      options: {
    //        root: '<%= yeoman.dist %>'
    //      }
    //    },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'scripts/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ngmin tries to make the code safe for minification automatically by
    // using the Angular long form for dependency injection. It doesn't work on
    // things like resolve or inject so those have to be done manually.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    ngtemplates: {
      fctrs: {
        cwd: "<%= yeoman.app %>",
        src: ['scripts/**/*.html'],
        dest: '.tmp/concat/scripts/templates.js'
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'styles/fonts/*',
            'statics/**',
            'test_data/**/*.json'
          ]
        },
        {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    processhtml: {
        options : {
            commentMarker : "process"
        },
      dist: {
          files: {
              '<%= yeoman.dist %>/index.html':['<%= yeoman.dist %>/index.html']
          }
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass:server'
      ],
      test: [
        'compass'
      ],
      dist: [
        'compass:dist',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'karma.conf.js',
        singleRun: true
      }
     }
    });


    grunt.registerTask('serve', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'configureProxies:server',     'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'bowerInstall',
      'concurrent:server',
      'autoprefixer',
      'configureProxies:server',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'bowerInstall',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'ngtemplates',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'rev',
    'usemin',
    'processhtml',
    'htmlmin'

  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};

所以我走錯了路,認為平滑是錯誤的 Uglify 或 concat 或縮小。

grunt serve沒有發生該錯誤,但僅在使用grunt build:dist創建了 dist 包后才發生

因此,在我創建一個 dist 包之前,我的 Angular 應用程序確實可以正常工作,這在某種意義上是一種欺騙。

問題是對我來說,我的 Index.html 文件中最初有一個<ng-include src="'scripts/navigation/navigationMobile.html'"></ng-include>元素。

在某些時候,我創建了一個自定義元素指令<my-nav></my-nav>它使用相同的templateUrl = scripts/navigation/navigationMobile.html但我忘記刪除<ng-include src="'scripts/navigation/navigationMobile.html'"></ng-include>元素從我的 Index.html 中被<my-nav></my-nav>替換。

無論出於何種原因,達到10 次 $digest() 迭代。 中止! 僅在運行grunt build並創建縮小的 Uglified vendor.js 文件后才發生,僅在使用grunt serve開發和測試時不會發生,但我不知道錯誤僅在grunt build之后出現的確切原因。

也許有人可以回答這個問題。

我注意到我們需要在兩種情況下給 ng-annotate 一個提示:

  • 當超類在構造函數上有可注入對象而子類沒有構造函數時,子類化(ES6 類);
  • 提供者的 $get 方法

摘要檢查錯誤是由僅在grunt build運行的任務發生的,或者與您從 ng-include 創建指令有關。

當您從 ng-include 更改為將其作為指令的模板時,angular 將暫停編譯直到下一個摘要,模板最終被加載時,即使它已經在 $templateCache 中。

參考: https ://docs.angularjs.org/api/ng/service/$compile(見templateUrl)

最后要注意的是,我會看一下 ngtemplates,因為它避免了通過線路的請求,並且當模板來自外部資源時,angular 會亂序編譯模板,這可能是您實現該指令的錯誤或者它的任何父級,它沒有正確調用 $compile 。

要修復此錯誤,只需打開 Gruntfile.js 文件並在任務 cssmin 和任務 uglify 中添加 extDot: 'last' 行。

前任:

cssmin: {
    all: {
        files: [{
            expand: true,
            cwd: srcDir,
            src: '**/*.css',
            dest: buildDir,
            ext: '.min.css',
            extDot: 'last'
        }]
    }
},
...
uglify: {
    all: {
        files: [{
            expand: true,
            cwd: srcDir,
            src: ['**/*.js', '!**/*-spec.js'],
            dest: buildDir,
            ext: '.min.js',
            extDot: 'last'
        }]
    }
},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM