If you want to include Gutenberg blocks, which are ReactJS based, in your WordPress plugin or theme, and you’re frustrated with the complication of Webpack and NPM, this tutorial is for you.

If you’re reading this, chances are you’ve already realized that writing in ReactJS is definitely simpler when using JSX. JSX is a javascript syntax which allows you to create HTML elements using an HTML tag-style syntax, as opposed to using createElement, which greatly de-bloatifies your code.

But in order to use JSX style syntax you have to include something called Babel on the page, which transpiles the JSX back in normal javascript so the browsers can understand and run it. This all happens behind the scenes.

Many tutorials out there are recommending that you use Webpack to pack Babel into your Gutenberg code. But Webpack can be a huge pain to set up and maintain, and Webpack is definitely not needed to do this, especially when we’re talking about WordPress. WordPress has something you’re probably already familiar with to handle this called wp_enqueue_script.

This WordPress function for loading javascript files onto your page allows for dependencies, which you can use instead of needing to use Webpack at all. Hooray!

Lets jump right into the code!

Loading the Javascript files

The first chunk of code is the PHP required to load the javascript files in the correct order. This is really where WordPress takes over to save you from needing Webpack, or any other similar code-bundling system.

Notice on lines 5, 14, 18, and 22 we are adding required JS files to an array. We then pass that array to the wp_enqueue_script function on lines 13, 17, 21, and 25. This is the important part that replaces Webpack. 

One other important piece of the puzzle here is line 30, where we modify the the way wp_enqueue_script works, and change the type of JS file to a Babel file. This is the required magic that makes it load the file correctly. 

The Javascript

The code above is just a completely static, and simple JSX Gutenberg block, to help get you started. Notice lines 12 and 17 are using JSX syntax. Here’s how it looks in the WordPress Block Editor:

Here’s our block showing up in the WordPress Block Editor
Here’s the output, which is a paragraph tag transpiled from JSX. 

For the scope of this article, I won’t go into further details on how to build a JSX Gutenberg Block for the WordPress Block Editor. But the simple instructions moving forward are to replace lines 12 and 17 with your own JSX code. 

To help you pull all of this together and get started, I’ve put together a boilerplate plugin with all of the above code ready to go here:

Happy block building! 🙂

Leave a comment

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