Including Files Conditionally

So far we’ve used the built-in prompts, but it might be nice if we let the users decide if they want us to generate a Gruntfile for their projects. We’ll assume they do by default, but we’ll give them the option to exclude it. We can do that with a custom prompt and a custom property.

First, ensure you’re back in the html5template folder that contains your template files. Then add the file Gruntfile.js to the root folder that contains the following code:

scaffolding/html5template/root/Gruntfile.js
 
module.exports = ​function​(grunt){
 
grunt.initConfig({
 
pkg: grunt.file.readJSON(​'package.json'​)
 
});
 
}

This sample Gruntfile loads the package.json file into the variable pkg. It’s a handy way to avoid repeating ourselves; we can now easily use the data in the package.json file inside of a Gruntfile. (We used this back in Using Values from Files.) Since this is such a common practice, we want this in our template’s Gruntfile.

Next, in template.js, in the prompts array, after the prompt for the name, author, and main file, add the following code to ask users if they’d like a Gruntfile:

scaffolding/html5template/template.js
 
{
 
name: ​'gruntfile'​,
 
message: ​'Do you want a Gruntfile?'​,
 
default​: ​'Y/n'​,
 
warning: ​'If you want to be able to do cool stuff you should have one.'
 
},

This is an example of a custom prompt. We use a JavaScript object that contains the name, the prompt’s message, the default value, and a warning message that is displayed to users if they don’t choose a valid option.

We’ve asked for the value, so now let’s use it. In the processing callback function, we’ll need to turn the “yes” or “no” value the user entered into a Boolean. So, above the init.copyAndProcess line, add this line:

 
props.gruntfile = /y/i.test(props.gruntfile);

Then right beneath that, add the logic to evaluate that variable, which is just a JavaScript if statement:

 
var​ files = init.filesToCopy(props);
*
if​(props.gruntfile){
*
props.devDependencies = {
*
'grunt': ​'~0.4.4'
*
};
*
}​else​{
*
delete​ files[​'Gruntfile.js'​];
*
}

If the user wants a Gruntfile, we make sure we add Grunt as a dependency to the package.json file. If he doesn’t want a Gruntfile, then we remove the Gruntfile from the list of files we’re going to copy. We always put every file possible into the template’s root folder, and then we filter out what we don’t want to copy.

Now when we run the command, we’ll get the new prompt. If we answer yes, we’ll get the Gruntfile, and Grunt gets added to our package.json file as a development dependency.

We can include or exclude files, but we can also include or exclude parts of our template files using a similar approach.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.75.117