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 Grunt can read the data from within a file using 'grunt.file.readJSON', and then have that data available with the following type of variable, '<%= pkg.value %>'.
What I'm wanting to do is to create a task with if/else options based on the variables from within the JSON file. What I'm unclear on is how to pass a Grunt variable '<%= pkg.value %>' into the JavaScript if statement in a way that it understands. I've tried passing it in the same Grunt format with '<%= %>', as well as stripping that part away and passing 'pkg.value', but neither seems to work.
If someone can shed some light on whether or not this can be done and how, I would greatly appreciate it. Thanks!
Instead of directly assign the grunt config in config
attribute, store it in a variable (gruntConfig
). Now you will be able to 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
}
});
};
When I have more time, I'll probably look into some additional ideas, but based on the ideas offered here, this is what I ended up going with 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
};
}
})()
}
});
};
Thanks, everyone, for your help!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With