Finding Things in Gutenberg Globals

Gutenberg is the project name for the new WordPress block editor, a multi-year effort that launched to the world last December. At its core Gutenberg is a collection of JavaScript modules providing internationalization, editor components, data stores, and so on. To ensure all plugins and themes use the same versions of these modules, they are exposed as (and accessed through) properties of the wp global JavaScript object.

Things have stabilized a lot since the early days of the project, but while the application was being built it was very common to install the latest version of the Gutenberg plugin only to find that a property or subproperty of wp — say, wp.editor.BlockControls, or wp.components.DropZone — had mysteriously disappeared, leaving your application with a console full of errors. This was a natural consequence of a large team iterating rapidly, but it was pretty frustrating to have to repeatedly track down the new location of the property you needed.

As noted above, things are a lot more stable now post-launch. But some packages do get migrated to new locations, and more importantly, the documentation does not always indicate how to import or access the functions and components in a code snippet.

This can all be solved with a small JS snippet to search the wp global and report where a module or function can be found:

/**
 * Debugging utility method to help trace which WP package exports a desired dependency.
 *
 * @param {String} exportName The export you are looking for, e.g. `compose` or `BlockIcon`.
 */
window.whatModuleExports = exportName => {
  Object.keys( window.wp ).forEach( packageName => {
    const keys = Object.keys( window.wp[ packageName ] );
    if ( keys.includes( exportName ) ) {
      console.log( `Export named ${ exportName } found in wp.${ packageName }!` );
    }
  } );
};

Paste this into your browser console, then call the function with the name of a property. You’ll see a message indicating which property of wp contains that specified property, component or function can be found:

> whatModuleExports( 'DateTimePicker' );
Export named DateTimePicker found in wp.components!

The code above only searches one level deep, but it could be extended to traverse the entire export tree.

I hope this will be useful to you the next time you’re trying to figure out which Gutenberg module exports the functionality you need!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.