Using Values from Files

Occasionally we’ll want to use some of the values from package.json in our projects, such as the project name, the project author, or the license information. Grunt provides a function called file.readJSON that, as you might be able to guess from the name, reads JSON data from a file and parses it into a JavaScript object. Add this to the configuration section of the Gruntfile:

files/recursive/deploying/Gruntfile.js
 
grunt.config.init({
*
pkg: grunt.file.readJSON(​'package.json'​),

It’s very common to see something like this in a Gruntfile. We can use these and other configuration values throughout the Gruntfile in a couple of ways. First, we can just access them as properties of the configuration, like grunt.config.get(’pkg.name’). But we can also use Grunt’s templating engine.

When we copy files to the source folder, let’s add a version.txt file that includes the name of the app and the version.

At the bottom of the copyFiles task, add this code:

files/recursive/deploying/Gruntfile.js
 
var​ content = ​'<%=pkg.name %> version <%= pkg.version %>'​;
 
content = grunt.template.process(content);
 
grunt.file.write(workingDirectory + ​'/version.txt'​, content);

The grunt.template.process function injects our configuration variables into the template string, giving us a new string that we can write into a file.

These template strings work automatically inside the Grunt configuration section too, without the need for the explicit call to grunt.template.process.. That means you can use templating to easily access configuration variables. For example, if you wanted to use the value of the copyFiles.options.manifest variable in another task’s configuration, you could reference it as <%= copyFiles.options.manifest %> instead.

Now, if we run grunt copyFiles again, in our working folder we’ll get a new file called version.txt that contains this:

 
deploying version 0.0.0

This technique is great for injecting the name of the project, the authors, or even the licensing information into the headings of files.

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

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