How do I enqueue a script to run inside the Gutenberg editor?

I’m using the Gutenberg editor as a replacement for a whiteboard in a classroom. I’m
able to make the classroom more interactive by having students work directly inside the
Gutenberg editor.

What a cool use of WordPress you describe there!

Is it possible to load this script inside the Gutenberg editor, so that while my students are editing the post we can also have the script working?

It seems that WordPress 5.0+ will provide us with two hooks for this:

/**
 * Fires after block assets have been enqueued for the editing interface.
 *
 * Call `add_action` on any hook before 'admin_enqueue_scripts'.
 *
 * In the function call you supply, simply use `wp_enqueue_script` and
 * `wp_enqueue_style` to add your functionality to the block editor.
 *
 * @since 5.0.0
 */
do_action( 'enqueue_block_editor_assets' );

and also for both editor and front-end:

/**
 * Fires after enqueuing block assets for both editor and front-end.
 *
 * Call `add_action` on any hook before 'wp_enqueue_scripts'.
 *
 * In the function call you supply, simply use `wp_enqueue_script` and
 * `wp_enqueue_style` to add your functionality to the Gutenberg editor.
 *
 * @since 5.0.0
 */
 do_action( 'enqueue_block_assets' );

Update: From the Gutenberg Handbook:

The enqueue_block_editor_assets hook is only run in the Gutenberg
editor context when the editor is ready to receive additional scripts
and stylesheets. There is also an enqueue_block_assets hook which is
run under both the editor and front-end contexts. This should be used
to enqueue stylesheets common to the front-end and the editor.

So you could try to enqueue your scripts in the callback of either of those hooks as needed. It’s also possible to add specific blocks as dependency.

Leave a Comment

tech