なっく日報

技術やら生活やらのメモ

npmをビルドツールとして動かす際に地味に役立つ知識

今、参画しているプロジェクトではgruntやgulp使わないで、npm run-scriptで頑張ろうとしているのでメモ。

タスクをまとめる

"scripts": {
  "build:css": "stylus assets/styles/main.styl > dist/main.css",
  "build:js": "browserify assets/scripts/main.js > dist/main.js",
  "build": "npm run build:css && npm run build:js"
 }

な感じ。npm run build:xx1 && npm run build:xx2 みたいに つなげていけばいいんですね。

タスクの区切りに:が使える

↑の例ですが、npm run build:css みたいに実行できることに「おっ」と思いました。

substackの下記ページを昔読んだのですが、
http://substack.net/task_automation_with_npm_run

{
  "build-js": "browserify browser/main.js | uglifyjs -mc > static/bundle.js",
  "build-css": "cat static/pages/*.css tabs/*/*.css > static/bundle.css"
}

みたいな、-区切りはあんま好みじゃないなあと思ってたんですが、普通に:も使えるんですね。

NPM Config Variables

 "name": "fooproject",
  "config": {
    "reporter": "xunit"
  },
  "scripts": {
    "test": "mocha test/ --reporter $npm_package_config_reporter"
    "test:dev": "npm run test --fooproject:reporter=spec"
  }

これ、package.jsonのconfigプロパティで設定したものが使えるのは便利かも。

-- で引数を渡せる

"scripts": {
  "test": "mocha test/",
  "test:watch": "npm run test -- -w",
}

な感じで。二回mocha test/ と書く必要はないですね。

まとめ

この辺のテクはぜひ取り入れていきたいです。

追記

今だと npm-run-all と組み合わせるともっとよい。

github.com