繁体   English   中英

带有 --filter 选项的 npm watch 不起作用

[英]npm watch with --filter option is not working

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

我的手表脚本如下:

"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 文件中……你能提供这个场景的工作代码吗? 我只想观看一个文件并在该文件更改时运行另一个脚本。

手表包的文档说:

'filter' - 您可以使用此选项提供一个函数,该函数为每个文件和目录返回 true 或 false,以确定该文件/目录是否包含在 watcher 中

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命令的<command> ,在我的情况下( 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;

链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM