簡體   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