当使用grunt-contrib-watch时,grunt-autoprefixer无限循环。

6

我正在学习 Grunt。我将使用 compass 来生成垂直节奏和图像精灵,并使用 autoprefixer 来添加 css3 样式的前缀。

这是我的 Gruntfile.js 文件。

module.exports = function(grunt) {
  var globalConfig = {
    sassDir: 'sass',
    cssDir: 'css'
  };

  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
  // Project configuration.
  grunt.initConfig({
    globalConfig: globalConfig,
    pkg: grunt.file.readJSON('package.json'),
    compass: {
      dev: {
        options: {
          sassDir: '<%= globalConfig.sassDir %>',
          cssDir: '<%= globalConfig.cssDir %>'
        }
      }
    },
    autoprefixer: {
      dev: {
        options: {
          browsers: ['last 2 versions']
        },
        src: '<%= globalConfig.cssDir %>/style.css',
        dest: '<%= globalConfig.cssDir %>/style.css'
      }
    },
    watch: {
      compass: {
        files: ['<%= globalConfig.sassDir %>/**/*.scss'],
        tasks: ['compass:dev'],
      },
      autoprefixer: {
        files: ['<%= globalConfig.cssDir %>/style.css'],
        tasks: ['autoprefixer:dev']
      },
      livereload: {
        options: { livereload: true },
        files: ['<%= globalConfig.cssDir %>/style.css']
      }
    }
  });

  // Default task(s) that will be run by invoking 'grunt' w/o args
  grunt.registerTask('styles:dev', ['compass', 'autoprefixer']);
  grunt.registerTask('default', ['styles:dev', 'watch']);
};

但每当我运行时

grunt

除了 grunt-contrib-watch 无休止地调用 grunt-autoprefixer 外,一切都按预期工作。

我刚开始学习 Grunt。这可能是我在 Gruntfile.js 中的错误配置。

希望你能在这里帮助我。

1个回答

10

将您的任务配置更改为:

watch: {
  compass: {
    files: ['<%= globalConfig.sassDir %>/**/*.scss'],
    tasks: ['compass:dev', 'autoprefixer:dev']
  },
  livereload: {
    options: { livereload: true },
    files: ['<%= globalConfig.cssDir %>/style.css']
  }
}

grunt-contrib-watch会在文件更新时运行任务,因为你的源文件和目标文件相同,所以它会变成一个无限循环。在compass任务构建css后,只需运行一次自动加前缀即可。希望这能帮到您。 :-)


如果您不介意的话,能否分享一些有关配置gruntfile.js的最佳实践技巧呢? :)谢谢。 - chanHXC
一旦你习惯了配置任务,你会发现有很多不同的插件可以自动化各种常见的开发工作。在这种情况下,我真的没有太多最佳实践可以参考,因为你已经为常见目录设置了配置,使用了matchdep技巧等。我发现只要阅读每个插件的文档,就可以很容易地让它们正常工作。但是一定要浏览npm存储库以寻找新的插件,有很多值得发现的东西 :-) - Ben

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