Using lodash and classnames with blocks in ES5

ES5 doesn’t have import and export statements, so when you create blocks in classic JavaScript, you are relying on the fact that the Gutenberg packages (wp-blocks, wp-element, etc.) are made available for you to use via the browser’s window object (the global namespace). When you enqueue your block scripts, you list these packages as dependencies.

But what about other dependencies? When you look at the examples in the Block Editor Handbook, you’ll see functions from other sources, like the classnames utility by Jed Watson and the assign function from the lodash library. How do you use these?

For lodash, things are simple. Gutenberg also comes with a copy of lodash that you can access through the global namespace. Add lodash to the list of dependencies when you enqueue your block scripts and start using lodash.assign() in your code. However, to use the classNames() function (note the capital N), you’ll need to download a copy of the script and add it to the page using <script> tags. IOW, enqueue the script as you would any other and make sure to add its handle to your block script dependencies.

Deciphering core blocks and other examples using Babel online

The problem: You’re not well-versed in JSX or ES6 syntax (like arrow functions), but the only example you can find of a custom block that does what you want to do is written in this style.

The solution: Copy the code snippet (in complete statements) that you don’t understand, head over to the Try It Out page on the Babel website, and paste the code into the left-hand box. In the right-hand box you’ll receive the transpiled code in ES5 and React. To use the code snippet in your project, replace all instances of React with wp.element.