3
1

More than 1 year has passed since last update.

【エラー】【Windowsの人は要注意】npm run watchが動かないときの解決方法

Last updated at Posted at 2021-11-26

脱gulpにむけて、npm-scriptsに移行中に、参考にしたコードを正確に書いたにも関わらずにうまく動かない。
ファイルの更新を監視するwatchを走らせた際に、なぜかエラーが発生する。

結論から言うと、
OSがWindowsの人は、シングルクーテーション「'」ではうまく機能しません!!
package.jsonの書き換える必要があります

参考にしたwatchは以下の書き方

package.json
"scripts":{ 
  "watch:server": "browser-sync start --server dist --files 'dist, **/*.html, !node_modules/**/*'",
  "watch:css": "watch 'npm run css' ./src/sass",
  "watch:js": "watch 'npm run js' ./src/js",
  "watch": "npm-run-all -p watch:*"
},

npm run watchをした場合の、エラー内容

terminal
$npm run watch

> Watching run
> Watching css'      
> Watching ./src/sass
C:\Users\...\node_modules\watch\main.js:73
    if (err) throw err;
             ^

[Error: ENOENT: no such file or directory, stat 'C:\Users\\...\\run'] {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'stat',
  path: 'C:\\Users\\...\\run'
}

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sample@1.0.0 watch:css: `watch 'npm run css' ./src/sass`
npm ERR! Exit status 1
npm ERR!
npm ERR!npm Failed at the study@1.0.0 watch:css script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
 ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sample@1.0.0 watch:js: `watch 'npm run js' ./src/js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sample@1.0.0 watch:js script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.


同じようにWatching ./src/jsもエラーがかえってきます。

どこが動いていないのか探る

browser-syncを指定したwatch:serverを個別にrunすると、ちゃんとブラウザがたちあがります。watchそのものが動いていないのではないようです。
npm run cssで指定したscssコンパイルも、npm run jsでjs圧縮も個別にrunするとちゃんと動きます。
npm-run-allで指定したコマンドですべてを動かすと、動きません。
ということで、

package.json
  "watch:css": "watch 'npm run css' ./src/sass",
  "watch:js": "watch 'npm run js' ./src/js",

この記述に問題がありそうです。

GitHubのissueに記述発見!

GitHub / npm watch#109

こちらによると、
windowsの人は、シングルクオーテーションの部分を以下のように書き換えます。

package.json
  "watch:css": "watch \"npm run css\" ./src/sass",
  "watch:js": "watch \"npm run js\" ./src/js",

Windowsの人は、文字列を\でエスケープが必要です!

無事、記述したnpm scriptsが動くようになりました。
ぜひ、Windowsでエラーが起こった人は上記をためしてみてください。

参考

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1