Grunt 构建导致 Angular 应用程序在 dist 上崩溃

Grunt build causing Angular app to crash on dist

我正在使用 G运行t 并执行 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: {}
      }
    }
  }
},

我在我的 G运行tJs 文件中设置了 mangle = false 但我怀疑 useMinPrepare js: ['concat', 'uglifyjs'] 改变了执行顺序并且 运行ning 在 ngAnnotate 可以 运行 当调用 useMin 时,即使我在 ngAnnotate.

之后调用 useMin

我是 G运行t 的新手,这个应用是从另一位开发者那里传给我的。

我发现这篇文章对我来说并不完全有意义,也不是似乎适用于我的 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 包后才发生

所以从某种意义上说,我的 Angular 应用程序在创建 dist 包之前确实可以正常工作。

我的问题是,我的 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> 旨在替换。

无论出于何种原因,达到了 10 次 $digest() 迭代。 Aborting! 仅在 运行 grunt build 和创建缩小的 Uglified vendor.js 文件后发生,仅在使用 grunt serve 开发和测试时不会发生,但我不知道错误仅在 grunt build 之后出现的确切原因。

也许有人可以回答。

我注意到我们需要在两种情况下给 ng-annotate 提示:

  • Subclassing (ES6 class) 当 super class 在构造函数上有可注入而 sub class 没有构造函数时;
  • 提供者的$get方法

摘要检查错误是由仅在 grunt build 中运行的任务引起的,或者与您从 ng-include 创建指令有关。

当您从 ng-include 更改为将其作为指令的模板时,angular 将暂停编译直到下一个摘要,当模板最终加载时,即使它已经在 $templateCache 中。

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

最后一点,我会看一下 ngtemplates,因为它避免了网络请求,并且 angular 当模板来自外部资源时乱序编译,它可以是您执行该指令或其任何父指令的错误,它没有正确调用 $compile。

To fix this error just open the Gruntfile.js file and add the line extDot: 'last' in both task cssmin and task uglify.

例如:

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'
        }]
    }
},