Grunt之watch详解

Grunt 之 watch 和 livereload

现在 watch 中已经集成了 livereload ,所以把它们放在一起说明。

watch 可以监控特定的文件,在添加文件、修改文件、或者删除文件的时候自动执行自定义的任务,比如 livereload 等等。

1. 安装

项目定义在 GitHub 上,地址:https://github.com/gruntjs/grunt-contrib-watch

可以通过 NPM 直接进行安装

npm install grunt-contrib-watch --save-dev

安装之后,需要在 Gruntfile.js 中添加任务的注册。

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

通过 grunt watch 运行 watch 任务。 

2. 配置 watch

与 connect 类似,在 watch 下面定义自己的子任务,下面的示例将会监控 src 目录下的任意 *.html 文件,在文件被修改之后,输出被修改的文件名。

这里通过 watch 的事件进行处理。

复制代码
'use strict';  

module.exports = function (grunt) {  

    // Project configuration.  
    grunt.initConfig({  

        watch:{
            start:{
                files: ['src/*.html']
            }
        }
    });

    grunt.event.on('watch', function(action, filepath, target) {
          grunt.log.writeln(target + ': ' + filepath + ' has ' + action);
    });
    grunt.loadNpmTasks('grunt-contrib-watch');
}
复制代码

我们启动 watch 任务,注意这个任务会持续监控。

PS C:studygrunt> grunt watch
Running "watch" task
Waiting...
start: srcindex.html has changed
>> File "srcindex.html" changed.
Completed in 0.001s at Sun Sep 06 2015 14:52:52 GMT+0800 (China Standard Time) - Waiting...

这里我们使用了 files 参数,这个参数可以为一个路径字符串或者一个字符串的数组,作为监控的目标。路径的写法可以参考:Grunt 之通配符

多数情况下,我们希望在文件发生变化之后,直接执行特定的任务,比如在修改了 *.js 的脚本文件之后,自动进行文件检查。这可以通过 tasks 来直接声明。

这里的 jshint 是我们后面会讲到的一个 javascript 语法检查库,现在还不能用呀。

watch: {
  scripts: {
    files: ['**/*.js'],
    tasks: ['jshint']
  },
},

这里我们自定义一个名为 hello 的任务。

tasks 是一个任务名称的字符串或者,一个任务名称的字符串数组,作为我们执行的任务。

复制代码
'use strict';  

module.exports = function (grunt) {  

    // Project configuration.  
    grunt.initConfig({  

        watch:{
            start:{
                files: ['src/*.html'],
                tasks: ['hello']
            }
        }
    });

    grunt.registerTask('hello', 'Hello, world task description.', function() {
            grunt.log.writeln('Hello, world.');
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
}
复制代码

3. 高级选项 

可以通过 options 配置更加详细的设置。

1. options.spawn

boolean 类型,默认 true。默认会创建一个新的子进程来执行触发的任务。通过设置为 false,可以使得触发的任务可以共享进程上下文,并且提高速度。但是,这会导致监控任务容易崩溃,所以,请尽量使用这个特性,在新的子进程中执行任务。

复制代码
watch: {
  scripts: {
    files: ['**/*.js'],
    tasks: ['jshint'],
    options: {
      spawn: false,
    },
  },
},
复制代码


2. options.interrupt

boolean 类型,默认为 false。还是和进程相关。

在文件发生修改的时候,会生成子进程来执行任务,默认的行为是对于每个目标来说,在上一个处理完成之后,仅仅生成一个新的子进程来执行任务。设置 interrupt 为 true,将会导致中止上一个进程,生成一个新进程来处理最后的变更。

复制代码
watch: {
  scripts: {
    files: '**/*.js',
    tasks: ['jshint'],
    options: {
      interrupt: true,
    },
  },
},
复制代码

3. options.debounceDelay

这是整数类型的参数,如果同样的文件或者路径被修改,需要等待多长时间才触发事件。默认 500 毫秒。

复制代码
watch: {
  scripts: {
    files: '**/*.js',
    tasks: ['jshint'],
    options: {
      debounceDelay: 250,
    },
  },
},
复制代码


 

4. options.event

字符串或者数组,默认为 'all'

指定监控目标的特定事件类型,可以为 'all', 'changed', 'added' 和 'deleted'.

复制代码
watch: {
  scripts: {
    files: '**/*.js',
    tasks: ['generateFileManifest'],
    options: {
      event: ['added', 'deleted'],
    },
  },
},
复制代码

5. options.reload

boolean 类型参数,默认为 false。

默认情况下,如果 Gruntfile.js 文件被监控,在这个文件被修改之后,会导致监控任务重新启动。并且重新加载 Gruntfile.js。

如果 reload 设置为 true,任何被监控文件的修改都会导致监控任务重新启动。除非你的 Gruntfile.js 依赖于其它文件,否则不使用这个参数。

复制代码
watch: {
  configFiles: {
    files: [ 'Gruntfile.js', 'config/*.js' ],
    options: {
      reload: true
    }
  }
}
复制代码

6. options.forever

boolean 类型参数,默认为 true。

这个整个任务级别的参数,不能在单个目标上配置。默认情况下,监控任务会处理 grunt.fatal 和 grunt.warn ,防止导致的退出监控问题。如果你不希望监控任务覆盖 grunt.fatal 和 grunt.warn ,可以将 forever 设置为 false。

options.atBegin

boolean 类型,默认为 false。

在监控任务启动的时候,自动触发对应的任务。

7. options.cwd

字符串或者对象类型,默认为 process.cwd()

设置当前的工作目录,默认为 process.cwd(),可以设置为字符串的目录来定义监控和产生的子任务的目录,或者一个对象来描述各自独立的路径。

 options: { 
    cwd: { 
        files: 'match/files/from/here', 
        spawn: 'but/spawn/files/from/here' 
    } 
}


 

4. livereload

这就是配合 connect 的 livereload 了。我们单独拿出来说明。

它是 options 的一个属性,类型为 boolean, 数值,或者配置对象。默认为 false

设置为 true 等价设置为 35729.

实际上,会启用一个支持重新加载的服务器,这个服务器工作在上述端口号上,通过这个服务器可以获取一个脚本,当文件被修改之后,通过这个脚本通知前端浏览器自动重新加载内容。

例如:

复制代码
watch: {
  css: {
    files: '**/*.sass',
    tasks: ['sass'],
    options: {
      livereload: true,
    },
  },
},
复制代码

启动之后,实际上在指定的端口上创建了一个服务器,如果访问的话,可以看到返回的信息。

访问:http://localhost:35729/

返回的内容

{"tinylr":"Welcome","version":"0.0.5"}

需要的话,还可以工作在 https 上,那就需要通过 key 和 cert 进行配置了。

复制代码
watch: {
  css: {
    files: '**/*.sass',
    tasks: ['sass'],
    options: {
      livereload: {
        port: 9000,
        key: grunt.file.read('path/to/ssl.key'),
        cert: grunt.file.read('path/to/ssl.crt')
        // you can pass in any other options you'd like to the https server, as listed here: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
      }
    },
  },
},
复制代码

更多内容可以查看 enable livereload on your HTML.

原文地址:https://www.cnblogs.com/koleyang/p/5567340.html