Properly add modern JavaScript to Gutenberg
Gutenberg is the “new” content editor that comes with WordPress 5.0 and later. It replaces TinyMCE that was used before. It had a rough start with the community but I think it’s time to surrender now and make friends with the fact that the use of classic editor plugin will come to an end soon.
If you want to extend your contents with additional data and functionality you probably need to add some UI. With the classic editor you could add php rendered UI with add_meta_box
. You still can add UI this way but its not recommended and it just looks out of place. Instead you should use JavaScript to extend the editors UI.
In this article we won’t actually add UI to Gutenberg but only have a look at how to properly add JavaScript files to the editor. You might say “Yeah, I know how to add JavaScript. What’s the point?”. The point is as follows.
Let’s imagine you’ve added a script file to your plugin in like /js/my-gutenberg-script.js. Depending on which parts of Gutenberg you want to use and extend there might be some dependencies like wp-data, wp-blocks, wp-element, wp-components
which your script needs.
DON’T 🚨
- Manually mange dependencies
- If you want to use modern JavaScript and jsx you need to config webpack or some other bundler to build the my-gutenberg-script.js from some source file
Instead DO ✅
Use wordpress/scripts to transpile your JavaScript source files into browser-compatible code. It will automagically generate an *.asset.php
file for you that manages dependencies and versioning.
- Dependencies are managed by
my-gutenberg-script.asset.php
- Versioning is managed by
my-gutenberg-script.asset.php
as well - Webpack configuration is ready to use
One important thing to mention: if you want to use dependency management like this, you have to npm install and use the dependency packages within your JavaScript files. For example:
npm install @wordpress/api-fetch --save
In your script:
import apiFetch from '@wordpress/api-fetch;
Now wordpress/scripts can manage this dependency for you.
You can use wordpress/scripts not only to transpile Gutenberg extensions but also anywhere else if you want to use react or fetch api in your plugins or themes code or if you just don’t want to config webpack yourself.
Some more information about the use of namespace in the code examples: https://medium.com/write-better-wordpress-code/use-namespace-in-plugins-and-themes-8a2eeb365d26
More information about the use of constants in the code examples: https://medium.com/write-better-wordpress-code/document-your-plugins-interface-in-code-c36e3e920707