Loading Gruntfile configuration from a JSON file

In this short gist we'll show you how to import data from an external json file when using Grunt task runner to build assets.

Loading Gruntfile configuration from a JSON file

The requirements are pretty simple, we’d like to tell Uglify to mangle a bunch of separate JavaScript files into one clean, minified file with sourcemaps to help debugging and learning.

But, the files are not all in one place and we don’t want to keep updating the Gruntfile configuration with complex glob rules – or perhaps the list of files changes based on configuration options defined somewhere else.

In the case of the Q Plugin, a file called q.module.json is generated when the settings are updated from inside the WordPress admin – you can see the specific action in the codebase – it is hooked to an ACF options page save routine.

Below is a very simplified version of the json file that is produced – showing a single file under the property javascript_path

Below is a slimmed-down gruntfile showing how we can use the grunt.file method to read the json file data and then assign an object of values from the javascript_path property to configuration

Notes:

  • The data stored in the file is converted to json format via the PHP function json_encode
  • The grunt.file method has a readJSON property which enables us to directly import the data from the json file
  • We can pass the javascript_path object to Uglify using Grunt variables like <%= config.q_modules.javascript_path %>
  • Enable logging via –verbose options when calling Grunt commands to get detailed feedback and locate issues.

Happy coding!

Gist List
Get the Gist of things
Read the Comments
Open on github

Comments

No comments on this article yet.

Add a Comment

Your email address will not be published. Required fields are marked *

These HTML tags work: <a href=""> <code> <strong> <pre>


Connect:
OR

Our Services
Validate your ideas before diving in. Consultancy
Dig deep, audit your data, prepare for action Discovery
Get everything in shape to smooth the project path. Shaping
Let us help you realize your imagination Design
Rock-solid WordPress tools, built to last. Development
Without water, the garden will not grow. Support


Projects
Quinta de Sant’Ana, Portugal
Quinta de Sant’Ana, Portugal

Quinta de Sant'Ana overlooks the picturesque village of Gradil with its cobbled streets, white washed houses and hospitable inhabitants.


Projects: View All or
Releases
Willow
Willow

Willow is a Logic~less Template Engine built for WordPress. Willow plays nicely with ACF, is quick to learn and developer-focused.


Releases: View All or