简体   繁体   中英

How to pass parameters to grunt tasks defined in external files using load-grunt-config?

My first post, so be kind please ^^
I'm using Grunt and load-grunt-config to split my tasks settings in several files which is working fine if i use this kind of settings :

./Gruntfile.js :

module.exports = function(grunt) {
  var path = require('path');
  var myParam = grunt.option('myParam') || 'responsive';
  // Project configuration.
  grunt.initConfig({
    ...
    require('load-grunt-config')(grunt);
    ...
  });
  ...
};

./grunt/concat.js :

var conf = require('../mytheme.config.json');
module.exports = {
  dist: {
    src: conf.theme.js.src,
    dest: conf.theme.js.dist + 'mytheme.bundle.js',
    options: {
    }
  }
};

My question is the following one : How can i pass the 'myParam' var to the external configuration in the 'concat.js' file ?

I didn't understand how to do it with the documenation from https://github.com/creynders/load-grunt-configs

Thanks

Ok i found something which is working for me :

./Gruntfile.js

module.exports = function(grunt) {
  // Define 
  var myParam = grunt.option('myParam') || 'responsive';

  // Plugins
  require('time-grunt')(grunt);
  require('jit-grunt')(grunt);
  require('load-grunt-config')(grunt, {
    configPath: path.join(process.cwd(), 'grunt/config'),
    jitGrunt: {
      customTasksDir: 'grunt/tasks'
    },
    data: {
      myParam: myParam // accessible with '<%= myParam %>'
    }
  });
};

./grunt/config/concat.js

var conf = require('../../mytheme.config.json');
module.exports = {
  dist: {
    src: conf.theme.js.src,
    dest: conf.theme.js.dist + '<%= myParam %>/mytheme.bundle.js',
    options: {
    }
  }
};

Hope it will help someone too.

On concat.js you could return a function, and then pass the parameter myParam

// Gruntfile.js ...
// ____________________> 
module.exports = function(grunt) {
  var path = require('path');
  var concat = require('./concat');
  var myParam = grunt.option('myParam') || 'responsive';

  concat.test(myParam);

  // Project configuration.
  grunt.initConfig({
    ...
    require('load-grunt-config')(grunt);
    ...
  });
  // ...
};

// concat.js ...
// ____________________> 
module.exports = {
    test: function(param){
        console.log(param); // logs myParam
        switch(param){
            case 'responsive':
                // do something (responsive)
                break;
            case 'mobile':
                // do something (mobile)
                break;
            default:
                // do something (default)
                break;
        }
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM