npm runに引数を渡そうとしてはまった話
npm run script
にコマンドライン上でオプションを付ける方法が分からず20分くらいはまり、腹が立ったので今後のために残しておく。
経緯
とあるプロジェクトをcloneしてきてwebpack-dev-server
を立てようとしたとき、webpack.config.js
にデフォルトで記述されていたhostとportは自分の環境では使えなかったので、コマンドライン上で起動時にhostとportを指定しようとした。
package.json
{ // ... "scripts": { "dev": "webpack-dev-server", // ... }, // ... }
$ npm run dev --host 192.168.xx.xx --port xxxx
しかしこの起動コマンドではwebpack.config.js
に記述されているhostとportで立ち上がってしまった。
調査
まずはnpmを使わず直接webpack-dev-serverで指定した場合の挙動を確認した。
$ ./node_modules/webpack-dev-server/bin/webpack-dev-server.js --host 192.168.xx.xx --port=xxxx
とするとまあ立ち上がる。腹が立つくらい華麗に立ち上がる。
という事はnpm run
側の問題だろうという事で公式ドキュメントを覗きに行くと、以下の記述が。
As of
npm@2.0.0
, you can use custom arguments when executing scripts. The special option--
is used by getopt to delimit the end of the options. npm will pass all the arguments after the--
directly to your script:
sh npm run test -- --grep="pattern"
なるほど。
渡したいコマンドは -- の後にかけ!! という事らしい。
解決
という事で以下のように変更。
$ npm run dev -- --host 192.168.xx.xx --port xxxx
無事動きました!
良かった良かった。
情報
https://docs.npmjs.com/cli/run-script