Grunt构建导致Angular应用在dist目录下崩溃

8

我正在使用Grunt并执行命令"grunt build"创建一个包含AngularJS应用程序的分发文件夹。

作为独立应用程序,我的应用程序运行良好。一旦我为应用程序创建一个分发版本,应用程序很快就开始崩溃。

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

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

我怀疑我的.tmp目录中有一个名为vendor.js的文件,没有正确地进行缩小、混淆和/或合并此文件,因为控制器依赖注入变量会将注入的控制器参数(例如"$scope")搞乱成 "a"。

注意,我正在使用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运行之前运行uglify,即使我在调用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'
  ]);
};

Angular 要求在进行代码压缩时,不要进行“混淆”操作。详见:http://google.com/search?q=angular+mangle - laggingreflex
1
运行 grunt serve:dist 命令,这将在 dist 文件夹中启动一个测试服务器,以便您可以查看错误是否发生在您要移动它到的应用程序之外。 - Terry
是的,我在使用grunt serve:dist时遇到了相同的错误。 - Brian Ogden
https://dev59.com/vGQm5IYBdhLWcg3w6SdR - Ruan Mendes
你应该在 <html> 标签上添加一个 ng-strict-di 属性,以强制 Angular 在依赖未正确注释时崩溃。这样,你至少可以看到是否是这个问题导致了你的问题,并更轻松地解决问题。 - Iso
在我的情况下,ng-strict-id会立即导致Angular崩溃,因为我的许多控制器没有正确注释。但是,如果你看到了我回答中的错误原因,对我来说,这个错误为什么只会在构建dist时发生而不会在grunt serve中发生,仍然是一个谜。 - Brian Ogden
3个回答

2
所以,我曾经错误地认为Uglify或concat或minification存在问题。
错误并没有出现在grunt serve中,但是只有在使用grunt build:dist创建dist package之后才会出现。
所以,在某种程度上,这是一种欺骗,我的Angular应用程序在创建dist package之前确实运行良好。
对我来说,问题在于我最初在Index.html文件中有一个<ng-include src="'scripts/navigation/navigationMobile.html'"></ng-include>元素。
在某个时候,我创建了一个自定义元素指令<my-nav></my-nav>,它使用相同的templateUrl = scripts/navigation/navigationMobile.html,但我忘记从Index.html中删除<ng-include src="'scripts/navigation/navigationMobile.html'"></ng-include>元素,而这个元素本应该被<my-nav></my-nav>替换。
由于某种原因,只有在运行grunt build并创建压缩、混淆的vendor.js文件之后,才会发生10 $digest() iterations reached. Aborting!错误。但是,当只是使用grunt serve进行开发和测试时,并没有发生这种情况。我不知道这个错误之所以只在grunt build之后出现的确切原因。 也许有人可以回答这个问题。

1
我注意到我们需要在两种情况下向ng-annotate提供提示:
  • 当超类的构造函数有可注入项且子类没有构造函数时进行子类化(ES6类);
  • 提供程序的$get方法

消化检查中的错误仅在grunt build中运行的任务中发生,或与您从ng-include创建指令有关。

当您将ng-include更改为指令模板时,即使它已经在$templateCache中,angular也会暂停编译,直到下一个消化,当模板最终加载时。

参考:https://docs.angularjs.org/api/ng/service/$compile(请参阅templateUrl)

最后,我建议您查看ngtemplates,因为它可以避免通过网络发送请求,并且当模板来自外部资源时,angular会按顺序编译模板,这可能是指令或其任何父级实现该指令的错误,未正确调用$compile。


0
要解决这个错误,只需打开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'
        }]
    }
},

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接