LoginSignup
0
0

More than 3 years have passed since last update.

npmコマンドで順番を無視した引数を使う方法

Last updated at Posted at 2020-02-21

npmコマンドを書いている中で、オプションをprocess.argv[2]と取りますが、
これの順番を決め打ちで取りに行かない方法を探した結果、argvを使うことにしました。

前提条件

  • npmがインストールされていること
  • package.jsonがあること

インストール

$ npm install -D argv

使い方

設定

touchコマンドでファイルを作成します。

$ touch test.js option.json

argvモジュールの読み込みと、option.jsonの読み込み、
argvのメソッドで引数のデータを取り込みます。

test.js
const argv = require('argv')
const option = require('./option')
const args = argv.option(option).run()

console.log(args)

引数で使うための名前と型、を設定するオブジェクトを設定します。
配列になっているため、必要な数だけオプションを増やすことが可能です。

option.json
[
  {
    "name": "option",
    "short": "o",
    "type": "string",
    "description": "あなたのスクリプトのオプションを定義します",
    "example": "'script --option=value' or 'script -o value'"
  }
]

npm run testコマンドでtest.jsを動かすように定義します。
オプションの設定をされていない引数は配列でtargetsとして記録されます。

package.json
{
  "scripts": {
    "test": "node test sample -o aaa"
  }
}

実行

npmコマンドを実行します。

$ npm run test

出力結果

{ targets: [ ‘sample’ ], options: { option: 'aaa' } }

オブジェクト形式でデータが取れているので、特定の値を取るときは、
args.options.optionという形式でaaaと取ることができます。

参考文献

この記事は以下の情報を参考にして執筆しました。

0
0
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
0
0