Can you pass a Grunt variable to a JavaScript function in a Grunt task?

Here is an example of what I'm looking for:

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 }; } })() } }); }; 

I know that Grunt can read data from a file using the file "grunt.file.readJSON" and then have this data with the following variable: "<% = pkg.value%>".

What I want to do is create a task with if / else options based on the variables from the JSON file. I don’t understand how to pass the Grunt variable '<% = pkg.value%>' into the JavaScript if statement in a way that it understands. I tried passing it in the same Grunt format with "<% =%>", as well as deleting this part and passing in "pkg.value", but it doesn't seem to work.

If someone can shed light on whether this can be done and how, I would really appreciate it. Thanks!

+5
source share
3 answers

When I have more time, I will probably consider some additional ideas, but, based on the ideas suggested here, this is what I have been going on for now.

 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 }; } })() } }); }; 

Thank you all for your help!

+1
source

Instead of directly assigning the grunt configuration in the config attribute, save it in the variable ( gruntConfig ). Now you can access it in the following code.

 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 } }); }; 
+1
source

Grunt has an API for reading files, which you can use something like this:

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']); }; 
0
source

Source: https://habr.com/ru/post/1239599/


All Articles