LoginSignup
4
4

More than 5 years have passed since last update.

Gruntのgrunt-execプラグインでNODE_ENVを指定してそれに応じて設定ファイルを読み込む

Last updated at Posted at 2013-05-16

npm install config --save
ってやるとconfigモジュールがインストールされる。

これは./configディレクトリ以下のファイルを読むので、そこに各環境ごとに必要な設定ファイルをyamlなどで書いておく。

Gruntfile.coffee
module.exports = (grunt) =>

    beforeEnv = (cmd)->
        return (env) ->
            if env?
                command = 'NODE_ENV='+env+' '+cmd
            else
                command = cmd
            console.log "exec : ", command, "\n"
            return command

    grunt.initConfig
        pkg: grunt.file.readJSON('package.json')

        exec:
            hoge:
                cmd: beforeEnv('node dest/main.js -arg huga')
                stdout: true

    grunt.loadNpmTasks('grunt-exec')

main.coffee
config = require('config')
console.log "main.js config : ", JSON.stringify(config), "\n"

console.log process.env.NODE_ENV

以上のようなファイルを書いておくと、

grunt exec:hoge:myenv と実行した時、
NODE_ENV=myenv node dest/main.js -arg huga というコマンドが実行されて
config/myenv.yaml が読み込まれる。

これをつかえば設定をちょっとだけ変えたコマンドを実行したい時に、
cp config/myenv.yaml config/yourenv.yaml したあと編集して
grunt exec:hoge:yourenv とすれば簡単に読み込む設定ファイルが変えられる。

NODE_ENVにこんな風に好き勝手な文字列を設定していいものなのかはよくわからないが、
マズかったらconfigファイル名を引数に応じて指定するようなコマンドにすればよさそう。

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