【问题标题】:npm watch with --filter option is not working带有 --filter 选项的 npm watch 不起作用
【发布时间】:2020-02-18 09:49:22
【问题描述】:

我正在尝试使用 npm watch 来观察文件中的更改并触发 package.json 文件中的另一个脚本....但它不起作用。

我的watch脚本如下:

"watch": "watch 'npm run start' './src' --filter='./testFilter.js'"

testFilter.js文件如下,只看testCode.js文件的变化:

 var watch = require('watch');

 watch.watchTree('./src/', function (f, curr, prev) {
    if (typeof f == "file" && prev === null && curr === null) {
      return("testCode.js");
    } else if (prev === null) {
      return("testCode.js");
    }
    return("testCode.js");
  })

当我运行npm watch 时出现以下错误。

/..../node_modules/watch/main.js:53
            if (options.filter && !options.filter(f, stat)) return done && callback(null, callback.files);
                                           ^

TypeError: options.filter is not a function
    at /.../node_modules/watch/main.js:53:44

我认为问题出在上面的 testFilter.js 文件中...您能否为这种情况提供一个工作代码?我只想查看一个文件并在该文件更改时运行另一个脚本。

【问题讨论】:

    标签: javascript node.js monitoring watch


    【解决方案1】:

    watch 包的 documentation 说:

    'filter' - 你可以使用这个选项来提供一个返回的函数 每个文件和目录的 true 或 false 以 决定是否 该文件/目录包含在观察程序中

    CLI USAGE:
    
        Usage: watch <command> […directory] [OPTIONS]
    
    
    OPTION FILTER:
    
        --filter=<file>
            Path to a require-able .js file that exports a filter
            function to be passed to watchTreeOptions.filter.
            Path is resolved relative to process.cwd().
    

    示例:

    这是一个工作示例,它允许执行定义为watch 命令的&lt;command&gt;,在我的情况下(npm run assets:renameJs),我想将文件 dist/original.js 重命名为 dist/renamed.js仅当 dist/original.js 文件更改时。

    这可以防止循环,因为没有此过滤器,每次重命名文件时都会触发监视。

    // ./package.json
    
    …
    “scripts”: {
        …
        "assets:renameJs": "mv dist/original.js dist/renamed.js || true",
        "myWatch": "watch \"npm run assets:renameJs\" ./dist --filter='npm-watch-myFilter.js'"
    }
    …
    
    // ./npm-watch-myFilter.js
    
    /**
     * @param  {string} f Filename
     * @param  {object} stat File System @see {@link http://nodejs.org/api/fs.html File System}
     */
    const myFilter = (f, stat) => stat.isFile() && f === 'dist/original.js';
    
    module.exports = myFilter;
    

    链接

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 2014-02-20
      • 1970-01-01
      相关资源
      最近更新 更多