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.
Lets jump right into the code!
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 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:
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! 🙂