Here is my solution to fixing the ‘wp’ not defined error that I was getting from my preprocessor tools.

If you happen to create you own script for WordPress, either Plugin, or Theme, you may also use preprocessor tools to build those scripts.

Problem

During one recent build, I happened to be running Gulp, which used a version of JShint to verify the quality of the Javascript that I was writing.

I recently came across a problem where JShint refused to validate perfectly valid script. The problem seemed to be that it wasn’t aware of a WordPress global JavaScript variable: wp

There is an easy fix for this, but it wasn’t that easy to find, for me anyway.

Firstly, this is the error message that I was getting, before I figured out that it wasn’t my code or Gulp.

js\script.js
line 20 col 20 'wp' is not defined.
line 20 col 49 'wp' is not defined.

!! 2 warnings

[19:16:23] 'jshint' errored after 1.69 s
[19:16:23] Error in plugin "gulp-jshint"

Now, I should have seen the 'jshint' errored part earlier and realised where the problem was.

Solution

To make jshint know about global variables, you need to find your .jshintrcfile, which is usually located in the root of your project.

Open this file with your Text Editor of choice. Check to see if the "globals" attribute is listed already. If not, you’ll need to add it. Add your new entry in accordance with the current alphabetical order.

The line you’ll need to add to let jshint know that wp is a global is as follows:

"globals": { "wp": true },

Remember, only add the trailing comma if it isn’t the last config entry in the file.

Save and run Gulp, Jshint, or whatever you use again, everything should be great.

Tags: , , , , ,

Join the conversation...

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