LoginSignup
69
39

More than 5 years have passed since last update.

npm run (npm run-script) コマンドで実行するスクリプトに引数を渡す。2017

Posted at

--記号を使う

npm runコマンドの末尾に--記号を書き、空白に続けて文字列を書くと、その文字列がスクリプトにそのまま渡されるようです。

package.jsonに下記のようなスクリプトが用意されている場合にpackage.jsonファイルを書き換えることなく、--host 0.0.0.0という引数を追加する方法を探していました。

package.json
{
  "scripts": {
    "start": "yarn check-env && ng serve"
  }
}

以下のようなコマンドを実行すると

npm run start -- --host 0.0.0.0

下記のように処理されるようです。

yarn check-env && ng serve --host 0.0.0.0

拝見した情報源

メモ書き

サイトには下記のような説明がされていました。

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:

npm@2.0.0からは、スクリプトの実行時にカスタム引数を使用できます。特別なオプション -- は、オプションの終わりを区切るためにgetoptによって使用されます。 npmはすべての引数をスクリプトの後に渡します:

どうやら、

  1. npmgetoptという仕組みを使って、コマンドラインに渡される文字列を解析している
  2. getopt--記号より後ろの部分は、1つの文字列として解釈する
  3. npmはこの仕組みを利用して--記号の後の文字列を取り出し、npm scriptの後ろに渡している

ということっぽいです。

下記のコマンドを

npm run start -- --host 0.0.0.0

下記の2つの部分に分けたのはgetoptの仕業で、

  • run start
  • --host 0.0.0.0

手に入れた文字列--host 0.0.0.0

yarn check-env && ng serve

の後ろに付け足して

yarn check-env && ng serve --host 0.0.0.0

にしたのはnpmの仕業ということのようですね。

69
39
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
69
39