Yeoman angular:Sass编译极其缓慢

7
我正在使用最新的Yeoman Angular生成器来启动一个项目。我想使用SASS和Compass,这是Yeoman默认提供的。
Compass的一个大缺点就是它非常慢。我已经包含了Twitter Bootstrap(SASS版本),在我的样式文件夹中有三个`.scss`文件,编译大约需要10-12秒。当使用实时监控时,速度略快(大约1秒)。
但是每次更改样式文件都要等待10-12秒,这太疯狂了。我找到了一些帖子(其中大多数是一年前的),但它们没有对我有所帮助。我还发现了这个项目 https://github.com/sindresorhus/grunt-sass,它用C++版本替换了原始的 https://github.com/gruntjs/grunt-contrib-sass,而不是使用Ruby编译。但缺点是它不支持Compass。
我希望有人能帮助我加速。 这是我的设置:

我正在使用grunt serve启动我的grunt服务器,实时监控*.js, *.scss文件,并在文件更改时触发重新加载。这是我的Gruntfile.js

// Generated on 2014-06-16 using generator-angular 0.9.0-1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.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);

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: 'dist'
  };

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

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer'],
        options: {
            spawn: false,
        }
      },
      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: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: false,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: false,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          '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
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath: new RegExp('^<%= yeoman.app %>/|../')
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}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: './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'
        }
      },
      server: {
        options: {
          debugInfo: true
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        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: {}
          }
        }
      }
    },

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

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   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,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.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.
    ngmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: '*.js',
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // 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}',
            'fonts/*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: '.',
          src: 'bower_components/bootstrap-sass-official/vendor/assets/fonts/bootstrap/*',
          dest: '<%= yeoman.dist %>'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // 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: 'test/karma.conf.js',
        singleRun: false
      }
    }
  });


  grunt.loadNpmTasks('grunt-sass');

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }
    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', 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',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngmin',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

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

启动我的Grunt服务器时,我得到了这个输出:

Running "serve" task

Running "clean:server" (clean) task
Cleaning .tmp...OK

Running "wiredep:app" (wiredep) task

Running "wiredep:sass" (wiredep) task

Running "concurrent:server" (concurrent) task

    Running "compass:server" (compass) task
    directory .tmp/styles/ 
       create .tmp/styles/colors.css (0.173s)
       create .tmp/styles/main.css (5.485s)
       create .tmp/styles/styles.css (5.725s)
    Compilation took 11.39s

    Done, without errors.


    Execution Time (2014-06-17 13:43:30 UTC)
    compass:server  12.9s  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 100%
    Total 12.9s

Running "autoprefixer:dist" (autoprefixer) task
File .tmp/styles/colors.css created.
File .tmp/styles/main.css created.
File .tmp/styles/styles.css created.

Running "connect:livereload" (connect) task
Started connect web server on http://localhost:9000

Running "watch" task
Waiting...

一个文件更改显示了这个日志:
>> File "app/styles/colors.scss" changed.

Running "compass:server" (compass) task
identical .tmp/styles/colors.css (0.033s)
overwrite .tmp/styles/main.css (4.074s)
overwrite .tmp/styles/styles.css (4.548s)
Compilation took 9.216s

Running "autoprefixer:dist" (autoprefixer) task
File .tmp/styles/colors.css created.
File .tmp/styles/main.css created.
File .tmp/styles/styles.css created.

Running "watch" task
Completed in 12.515s at Tue Jun 17 2014 15:48:47 GMT+0200 (CEST) - Waiting...

正如您所看到的,初始启动大约需要13秒,文件更改需要约9秒。

有什么想法可以加快速度吗?


更新

我稍微尝试了一下,这可能会有所帮助。它不能解决编译速度慢的问题本身,但可以加快速度:

  • 如果您不需要Bootstrap SASS版本,请跳过并切换到普通的CSS版本。这将显著减少编译时间。
  • 如果您需要SASS版本,请查看bootstrap.scss文件(无论是在您的bower_components/bootstrap-sass-official文件夹中还是手动下载的位置)。也许有一些组件是您不需要的,所以您可以跳过一些文件。在您的主SCSS文件中,您将像这样包含bootstrap:@import "bootstrap-sass-official/vendor/assets/stylesheets/bootstrap.scss";。查看此文件,并将仅需要的内容复制到您的主SCSS文件中(并确保更改路径)。
  • 确保您正确使用@import语句。默认情况下,所有没有文件名前缀_的文件都会被Grunt编译和包含。通常,您会为整个应用程序使用一个文件,例如styles.scss,或者如果您想将其分开,则使用几个文件,例如page1.scss、page2.scss...。如果您包含其他文件,例如@import 'colors.scss';,请确保文件名为_colors.scss。否则,colors.scss也会被Grunt编译,然后由于@import语句再次编译。这会减慢您的编译过程。

但是,这些只是解决方法,并不能加速编译本身。因此,我们仍在寻找解决方案。


1
我们的团队正在寻找合适的解决方案,最终选择了foundationcss和compass,因此我们必须使用grunt-contrib-sass(Ruby)。我希望未来能说服大家使用bourbon + grunt-sass(libsass)。 - Vincent De Smet
1
@Vincent:我更新了我的答案,并添加了一些提示来减少SASS编译过程的复杂性。也许这对你有所帮助(如果你找到了任何超级快速的SASS编译库,请告诉我;) - 23tux
对于foundationcss,我实际上可以使用ruby foundation gem生成一个-libsass版本,它带有一个grunt文件。我可以将其与我的angular-generator grunt文件合并,并摆脱compass。(尚未完成) - Vincent De Smet
@23tux,你是否使用某种虚拟化技术(Virtualbox、VMware或者不知道它们但是使用Vagrant)?还是这个问题出现在你的主机上(桌面电脑)? - czerasz
1个回答

2
您可以使用与libsass完全兼容的compass-mixins替换compass,并使用compass-importer将所有原始compass @import更新为新的。当我将一些compass项目迁移到libsass时,将编译时间从约30秒缩短到约350毫秒。

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