Issue with using Underscore in WordPress

I have read in another SO post that Underscore.js is including in WordPress by default. I am using it to test if a variable is defined but get this in the browser console:

pluginAdminPage.js:32 Uncaught ReferenceError: _ is not defined
    at pluginAdminPage.js:32
(anonymous) @ pluginAdminPage.js:32

_.VERSION // .VERSION even autofills. So then the browser has the library imported?
"1.8.3"

The code it refers to:

if (_.isUndefined(module) === false) {
  module.exports.func = func;
}

Phpstorm lints _ and isUndefined yellow which may suggest a lack of library import.

I then tried to explicitly enqueue Underscore but this did not change the browser error messages:

function loadAdminScripts() {
  wp_register_style(
    'admin-style',
    plugins_url('admin-style.css', __FILE__)
  );
  wp_enqueue_style('admin-style');
  wp_enqueue_script('jquery');
  wp_enqueue_script('underscore');
}
add_action('admin_enqueue_scripts', 'loadAdminScripts');

What step(s) am I missing to get Underscore working?

2 Answers
2

You need to set it as a dependency for your script, this is the best way you can make sure, Underscore.js is loaded before your script (which means, the methods will be available).

function loadAdminScripts() {
  wp_register_style(
    'admin-style',
    plugins_url('admin-style.css', __FILE__)
  );
  wp_register_script(
    'pluginAdminPage',
    plugins_url('pluginAdminPage.js', __FILE__),
    [
      'jquery',
      'underscore',
    ]
  );

  wp_enqueue_style('admin-style');
  wp_enqueue_script('pluginAdminPage');
}
add_action('admin_enqueue_scripts', 'loadAdminScripts');

Check the Code Reference on wp_register_style for more information.

Leave a Comment