2016-10-11 46 views
1

我的第一篇文章,所以被親切請^^
我使用步兵和負載咕嚕-配置如果我使用這種設置分割在幾個文件中我的任務設置,這是工作的罰款:如何使用load-grunt-config將參數傳遞給外部文件中定義的grunt任務?

./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: { 
    } 
    } 
}; 

我的問題如下:如何將'myParam'var傳遞給'concat.js'文件中的外部配置?

我不知道如何與documenation從https://github.com/creynders/load-grunt-configs

感謝

+0

你將有多少任務?我認爲沒有必要在很多文件中打破它,如果只使用Gruntfile.js就足夠了。 – Raduken

+0

@Raduken這裏的重點是在任務執行期間將變量傳遞給外部文件,而不是事實上分離任務文件。 我想從Gruntfile的「concat.js」中使用「myParam」var,現在它不起作用。 –

回答

0

好吧,我發現了一些東西,爲我工作:

./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: { 
    } 
    } 
}; 

希望它能幫助別人。

+0

我找到了另一個解決方案。 問題是在少數任務中使用相同的變量。 所以對我來說最好的解決方案是用grunt.config.set('myParam',myParam)設置一個grunt配置。 因此,它可以在其他任務中使用:grunt.config('myParam'); 我應該使用着名的RTFM :) –

0

concat.js你可以返回一個函數,然後傳遞參數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; 
     } 
    } 
}; 
相關問題