3
votes

i want to create some kind of task where i can read custom configs from different json files, and replace stuff inside my coffee-source files with contents of the json files, and concatenate the source-files.

my projekt-setup:

  • ./src

    • file1.coffee
    • file2.coffee
  • ./config

    • /folder1

      • development.json (contains: {"key": "value1"}
      • production.json (contains: {"key": "value2"}
    • /folder2

      • development.json (contains: {"key": "value3"}
      • production.json (contains: {"key": "value4"}
  • ./dist

    • package-name.coffee
    • package-name.js

file1.coffee contains

myVar = '@@putkeyhere'
version = '@@version'
...

i have the grunt concat task running for itself configured and working:

concat: {
  dist: {
    src: ['<banner>', './src/*.coffee'],
    dest: './dist/<%= pkg.name %>.coffee'
  }
},

i have got the grunt-replace task (the replacement of version and so on is already working when i run "grunt replace" on already concatenated files)

replace: {
  dist: {
    options: {
      variables: {
        'created': '<%= grunt.template.today("dd.mm.yyyy HH:MM:ss") %>',
        'environment': 'dev',
        'version': '<%= pkg.version %>'
      },
      prefix: '@@'
    },
    files: {
      'dist/': ['./dist/<%= pkg.name %>.coffee']
    }
  }
},

and finally the coffee compile task:

coffee: {
  compile: {
    files: {
      './dist/<%= pkg.name %>.js': ['./dist/*.coffee']        
    }
  }
}

all tasks work for themselves, but i need to read from the config-json files replace the contents into concatenated coffee-files, and then compile all files to js.

i tried something like this, but that doesnt feel right:

grunt.registerTask('mytask', '', function (env) {

  env = env || 'development';
  if (env !== 'development' && env !== 'production') {
    grunt.log.error("'" + env + "' is not valid environment");
    return false;
  }

  var c = grunt.option('c');
  if(c) {

    // if i run the task "grunt mytask:production -c folder2 it should read
    // ./config/folder2/development.json
    // that works that way, but i dont think this is a good solution
    var config = grunt.file.readJSON('./config/' + c + '/' + env + '.json')


  } else {

     // here i need to iterate for all folders in ./config, and do stuff for all
  }

});

is the multiTask an option? but how do read dynamically from the config.json files?

appreciate your help!

1

1 Answers

0
votes

I found a plugin that can help you to accomplish that - https://github.com/outaTiME/grunt-replace