Working with package.json data in Grunt tasks

Working with package.json data in Grunt tasks

In this post, I want to share a quick tip that I’ve discovered recently while playing with Grunt. You probably know that you can access data from package.json and use it in a grunt task right?

I am sure you do, but in case you don’t, here’s a quick example. Let’s take a simple package.json:

{
  "name": "projectname",
  "version": "0.1.0",
  "devDependencies": {
    "grunt": "~0.4.5",
   }
}

In this case to get a project name you would write:

<%= pkg.name %>

What’s  interesting, is that you can modify the value inside

<%= %>

This means you can, for example, use the project name in upper case:

<%= pkg.name.toUpperCase() %>

Use case

Let’s say you have a little starter theme with basic functionality. Usually, you need to change its name for every new project.

And as you know, changing a theme name “the right way” includes changing many things: textdomains, function prefixes,  DocBlocks and sometimes constants (which are usually uppercase).

Instead of doing a manual search and replace  every single time, you can create a simple grunt task that would use project name from package.json and rename all necessary theme files using grunt-text-replace. In this case knowing how to work with package.json data may be very useful.

Of course, it is just a single example. Have other ideas or use cases? Please share in comments.

Heads up! This is an archived website I decided to keep for history. Head on to a new one →