你可以传递一个Gruntvariables到一个Grunt任务中的JavaScript函数吗?

这里是我正在寻找的一个例子:

module.exports = function(grunt) { grunt.initConfig({ config: grunt.file.readYAML('_config.yml'), // example variable: <%= config.scripts %> copy: { scripts: (function() { if (config.scripts === true) { // I want to target <%= config.scripts %> return { expand: true, cwd: '<%= input %>/_assets/js/', src: '**/*.js', dest: '<%= output %>/assets/js/' }; } else { return { // do nothing }; } })() } }); }; 

我知道Grunt可以使用'grunt.file.readJSON'从文件中读取数据,然后使用以下types的variables“<%= pkg.value%>”来获取该数据。

我想要做的是使用基于JSON文件中的variables的if / else选项创build任务。 我不清楚的是如何将Gruntvariables'<%= pkg.value%>'传递到JavaScript if语句中。 我试着用相同的Grunt格式来传递它,同时剥去那个部分并传递'pkg.value',但是两者似乎都不起作用。

如果有人能够说明这是否可以做到以及如何做,我将不胜感激。 谢谢!

不要直接在config属性中指定gruntconfiguration,而gruntConfig其存储在variables( gruntConfig )中。 现在你可以在下面的代码中访问它。

 module.exports = function(grunt) { // store your grunt config var gruntConfig = grunt.file.readYAML('_config.yml'); // init `script` with an empty object var script = {}; if (gruntConfig.script) { script = { expand: true, cwd: '<%= input %>/_assets/js/', src: '**/*.js', dest: '<%= output %>/assets/js/' }; } // Init Grunt configuration grunt.initConfig({ config: gruntConfig, copy: { scripts: script } }); }; 

当我有更多的时间时,我可能会研究一些额外的想法,但基于这里提供的想法,这是我现在结束了。

 module.exports = function(grunt) { var config = grunt.file.readYAML('_config.yml'); grunt.initConfig({ copy: { scripts: (function() { if (config.scripts) { return { expand: true, cwd: 'input/_assets/js/', src: '**/*.js', dest: 'output/assets/js/' }; } else { return { // do nothing }; } })() } }); }; 

谢谢大家的帮助!

Grunt有一个API来读取文件,你可以使用这样的东西:

test.json

 { "fruit": "apple" } 

Gruntfile.js

 module.exports = function(grunt) { grunt.initConfig({ ... }) grunt.registerTask('sample-task', function() { var test = grunt.file.readJSON('./test.json'); if (test.fruit === 'apple') { // do this one thing } else { // do something else } }); grunt.registerTask('default', ['sample-task']); };