watch 的配置
watch : { less :{ files:['css/*.less'], tasks:['less'] }, livereload:{ options:{ livereload:true }, files:['css/*.css','js/*.js',./*.html] } }
tasks,定义当文件发生变化时,执行哪些任务
options 中包含可选参数,具体查看https://github.com/gruntjs/grunt-contrib-watch
其中,livereload 启动livereload 服务器,具体端口可以进行配置
以上watch 的配置,意义是:当页面资源文件发生变化时,livereload 服务器控制客户端刷新。当less文件发生变化时,执行less任务,生成.css文件,进而刷新页面。
watch 启动了livereload 服务器,那客户端如何同livereload 之间通信呢?
利用grunt-contrib-connect 中间件,在返回的body中,添加同livereload 服务器通信的脚本
connect: { options: { port: 9000, // change this to '0.0.0.0' to access the server from outside hostname: 'localhost', base: '.' }, livereload: { options: { middleware: function (connect, options) { return [ require('connect-livereload')({ port:35737 }), // Serve static files. connect.static(options.base), // Make empty directories browsable. connect.directory(options.base) ]; } } }, },
这里用到了connect-livereload 模块,负责在页面中加入与livereload 通信的脚本。如:
<script src="http://localhost:35738/livereload.js?snipver=1" type="text/javascript"></script>
最终的Gruntfile.js 如下:
/* * qqfn * a project * Copyright (c) 2013 who are you */ 'use strict'; module.exports = function (grunt) { // Project configuration. grunt.initConfig({ //connect connect: { options: { port: 9000, // change this to '0.0.0.0' to access the server from outside hostname: 'localhost', base: '.' }, livereload: { options: { middleware: function (connect, options) { return [ require('connect-livereload')({ port:35737 }), // Serve static files. connect.static(options.base), // Make empty directories browsable. connect.directory(options.base) ]; } } }, }, watch: { allfiles: { files: ['*.html','css/**','js/**'], tasks: ['less:development','cssmin'], options:{ livereload: 35737 } } }, cssmin: { combine:{ files:{ 'goline/main.css' : ['css/main.css'] } } }, less : { development:{ files:{ "css/main.css" : "css/main.less" } } }, uglify:{ my_target: { files: { 'goline/main.combo.js': ['test/dist/js/main.combo.js'] } }, jquery:{ files:{ 'goline/jquery.js':['js/jquery.js'] } } } }); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-livereload'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-watch'); //grunt.loadNpmTasks('connect-livereload'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. // By default, lint and run all tests and build. //grunt.registerTask('default', ['jshint', 'test', 'build']); // //server grunt.registerTask('default', function () { grunt.task.run([ 'connect', 'watch']); }); grunt.registerTask('goline', function () { grunt.task.run(['cssmin','uglify']); }); };
参考:
http://my.oschina.net/liuyong25/blog/140110