MEANスタック入門(5) タスクランナーの代わりにnpm-scriptsを使う
ビルドから実行までを自動化するのに、gulpやgruntなどのタスクランナー代わりにnpm-scripts
を使います。
npm-scriptsの設定
開発時
開発時はそれぞれコードの変更を監視して、自動でトランスパイルを走らせます。
Angularをng server
で実行し、Express側のトランスパイルをtsc
で実行します。
また、変更を検知して自動でコンパイルするために別途tsc
を-w
オプション付きで実行し、それによりソースが書き換わった際に自動で再起動するnodemon
を実行します。
コマンドは順を追うと以下の通りです。
$ ng server --proxy-config proxy.conf.json $ tsc -p ./server $ tsc -w -p ./server $ nodemon dist/server/bin/www.js
上記をpackage.json
のscripts
に設定し、npm-run-all
を使って並列実行します。
必要なnpm-run-all
とnodemon
をインストールしておきます。
$ npm install --save-dev npm-run-all $ npm install --save-dev nodemon
サーバ開始前にTypeScriptのトランスパイルを実行させたいので、run-s
を使って直列につなぎます。
次にそれぞれのサーバ開始と監視開始をrun-p
を使って並列に実行します。
Angular側の作業順序はng server
コマンドに任せます。
また、ついでにMongoDBの起動もここでやっておきます。
package.json
"scripts": { "start": "run-s tsc start:p", "tsc": "tsc -p ./server", "start:p": "run-p start:mongo watch:*", "start:mongo": "mongod --config \"C:/MongoDB/Server/3.4/bin/mongodb.config\"", "watch:ng": "ng server --proxy-config proxy.conf.json", "watch:tsc": "tsc -w -p ./server", "watch:nodemon": "nodemon dist/server/bin/www.js" }
npm run
で実行すると、上記手順が一度に実行されます。
$ npm run start
公開用
それぞれ単純にビルドします。
package.json
"scripts": { "build": "run-p tsc build:ng", "build:ng": "ng build --prod" }
同じくnpm run
で実行します。
$ npm run build
これだけでもかなり効率化されました。