首页 > 如何用grunt创建compass和自动刷新

如何用grunt创建compass和自动刷新

这是我的配置gruntfiles文件

module.exports = function(grunt) {

// 1. 所有的配置将在这里进行
grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    connect: {
        options: {
            port: 8000,
            hostname: '127.0.0.1', 
            livereload: 35729 
        },
        server: {
            options: {
                open: true, 
                base: [
                    'website' 
                ]
            }
        }
    },
    compass: {
          dist: {
            options: {
               config: 'config.rb'
            }
          }
    },
    watch: {
        livereload: {
            options: {
                livereload: '<%=connect.options.livereload%>' //监听前面声明的端口  35729
            },

            files: [ 
                'website/*.html',
                'website/css/{,*/}*.css',
                'website/js/{,*/}*.js',
                'website/images/{,*/}*.{png,jpg}'
            ]
        },

    }

});

// 3. 我们在这里告诉grunt我们将使用插件
//grunt.loadNpmTasks('grunt-contrib-concat');

//grunt.loadNpmTasks('grunt-contrib-uglify');

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

grunt.loadNpmTasks('grunt-contrib-compass');

grunt.loadNpmTasks('grunt-contrib-watch');

grunt.registerTask('serve', ['connect:server','compass:dist','watch']);

这是我的package.json文件

{
  "name": "ruiche.com",
  "version": "0.1.0",
  "description": "",
  "devDependencies": {
    "grunt": "~0.4.1",
    "grunt-contrib-compass": "^1.0.1",
    "grunt-contrib-concat": "^0.5.0",
    "grunt-contrib-connect": "^0.8.0",
    "grunt-contrib-uglify": "^0.6.0",
    "grunt-contrib-watch": "^0.6.1",
    "package": "^1.0.1",
    "package.json": "0.0.0"
  },
  "repository": "git://github.com/gruntjs"
}

那么问题来了,我这个grunt serve启动的时候,compass会编译一次config.rb文件,之后sass文件有修改的时候再也不做事了,这是什么原因??


REQUIREMENT

grunt serve启动时当.sass文件发生变化时,自动编译更新.css文件

HOWTO

我觉得你首先要弄明白是哪个任务使得grunt serve任务执行时能够检查文件变化并进行编译。
在这里是watch这个task,关于grunt-contrib-watch请点击查看文档

TODO

watch的任务中需要指定对.sass文档的编译任务

这里参考grunt-contrib-watch的官方给出的代码

https://github.com/gruntjs/grunt-contrib-watch/blob/master/docs/watch-examples.md#enabling-live-reload-in-your-html

grunt.initConfig({
  sass: {
    dev: {
      src: ['src/sass/*.sass'],
      dest: 'dest/css/index.css',
    },
  },
  watch: {
    sass: {
      // We watch and compile sass files as normal but don't live reload here
      files: ['src/sass/*.sass'],
      tasks: ['sass'],
    },
    livereload: {
      // Here we watch the files the sass task will compile to
      // These files are sent to the live reload server after sass compiles to them
      options: { livereload: true },
      files: ['dest/**/*'],
    },
  },
});

CONCLUSION

好好读读grunt-contrib-watch的官方文档,你要的都在里面

【热门文章】
【热门文章】