Grunt JSON Directive
Grunt supports a number of directives out of the box. These are callable from within you
grunt.js file. The gruntfile template uses one of these directives like so:
1 2 3 4
This is making the contents of your
package.json file available to your grunt config. And this is what we wanted! So, if I want to put the version of my app into some grunt task config, I can use it like so:
1 2 3
This would already be enough – it it worked all the time! Turns out it doesn’t [tear].
This syntax (“<%= someVar %>”) is referred to as a grunt.template. It is based on underscore’s template function.
Grunt Plugin Support
It turns out that all plugins are not created equal. Some plugins do not support this syntax at all. I wrestled with mainly two plugins
As far as I can tell, neither plugin supports
grunt.template. Lameo. In the case of
grunt-jade, I actually switched plugins to
grunt-contrib-jade, which states explicit support for
grunt.template in the docs. Other than the docs or trying it out, I otherwise don’t know how to determine support.
Access package.json Directly
Where I couldn’t find a plugin that explicitly supported
grunt.template, I needed another solution. Guided by the power of Google, I ran across a good Stack Overflow post on getting
package.json values into the
The post illuminated my dim mind: Grunt runs in node. Do what you would do in node.
Thusly, I just require the
package.json file, and it is available. Voila. Who needs a stinkin template directive? And it looks like:
1 2 3 4
My one departure from the Stack Overflow suggestion was to use a different variable name on the require statement (‘package’ -> ‘pkgJson’). ‘package’ is a keyword that doesn’t pass linting.
Grunt access package.json
As it turns out, Grunt has not problem accessing
package.json) is pure genius. And genius that is easily accomplished? – noteworthy indeed.