How to Start Block Development with Scaffolding

Can you believe that it’s been two years already when Gutenberg got included in the WordPress core? In the meantime, the block editor has matured significantly. Using blocks steadily remains the primary approach to enrich the way users create content with WordPress. Some new exciting options let you defer the decision to build custom blocks. Those are among others  Block Directory, block patterns, or the preexisting reusable block feature. Indeed, they speed up the process of publishing posts and pages. However, I don’t plan to discuss here these types of capabilities.

Instead, I want to focus on the case when you decide to build a block. You might ask, why would you want to do it? Before anything else, it can be just for fun or to learn what the block editor has to offer. Later, it usually doesn’t take much time to discover that the WordPress core is missing a service integration you want or a layout element you often use. In the future, possibilities will become endless when the block-based full site editing rolls out.

I’m aware of how challenging it might be to make the first step and start developing inside the JavaScript-based architecture. It applies even when you have strong PHP background. That’s why the team behind Gutenberg provides a set of official WordPress block development tools – designed to make the experience more streamlined. I will show how to make the most of the scaffolding command, which will let you save hours when building the first block.

ECMAScript 5

If you are familiar with ESNext and JSX, you can skip to the Block Scaffolding section.

First, I’d like to discuss a strategy that the WordPress Core team incorporated to make it easier to start working with Gutenberg. It’s still possible to program using ECMAScript 5 (or ES5 for short) for the convenience of those with little or no experience with modern JavaScript. This well-established edition of JavaScript standard can run straight in the vast majority of browsers and does not require an additional build step. It’s also what most of the WordPress plugins or themes would use in the past.

You can follow the same approach to start experimenting with your plugin or theme quickly. To add your first block to the editor, it’s enough to paste the following code snippet in your browser’s Console.

( function( wp ) {
	var el = wp.element.createElement;
	var __ = wp.i18n.__;
	var registerBlockType = wp.blocks.registerBlockType;
	registerBlockType( 'gziolo/my-first-block', {
		title: __( 'My first block', 'gziolo' ),
		category: 'widgets',
		edit: function() {
			return el(
				'div',
				{},
				__( 'My first block', 'gziolo' )
			);
		}
	} );
} )( window.wp );

The example for the Chrome DevTools Console:

Block registration in the browser

Block Scaffolding

In practice, it’s a bit of work to make your block useful. That’s why there is a block scaffolding tool (aka boilerplate, generator, or starter kit) to ease the process. The idea behind it is to kickstart an initial project structure using all available best practices. There is @wordpress/create-block npm package that generates PHP, JavaScript, and CSS code—and everything else you need to start implementing your WordPress plugin.

This tool can be executed from the command line using the npx command. It offers a quick-start mode that lets you pass a slug that then becomes both the target location for the generated files and the internal block name.

npx @wordpress/create-block my-first-block

Finally, you can install and activate the scaffolded block like any other plugin on your WordPress site.

ESNext and JSX

I must emphasize the fact that the JavaScript ecosystem has flourished in recent years. There is now a magnitude of newly introduced language features and accompanying tools. The downside is that starting a new JavaScript-based project became a big challenge on its own. Regardless, I still strongly recommend getting familiar with the build tools and set up a development environment to use ESNext and JSX syntaxes. Despite an extra effort required and a steep learning curve, modern JavaScript enables a simpler code that is easier to read and write.

import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';

registerBlockType( 'gziolo/my-first-block', {
	title: __( 'My first block', 'gziolo' ),
	category: 'widgets',	
	edit() {
		return (
			<div>{ __( 'My first block', 'gziolo' ) }</div>
		);
	},
} );

Some browsers cannot interpret or run all available ESNext features. All of them won’t understand custom JSX syntax at all. That’s why we use a transformation step to convert this code back to the representation that all supported browsers can understand. In the case of WordPress, it’s still ES5-based JavaScript.

Reusable Scripts

I’m sure you won’t find it surprising to tell you that the Gutenberg project internally uses the best tools and the latest language features. Now, you might ask a question – can I use all that to develop plugins or themes for WordPress? The answer is, of course, yes. There is even a useful pattern that can simplify developers’ life here – it’s called reusable scripts.

The idea boils down to moving all the necessary configurations and scripts to one single tool dependency. @wordpress/scripts is such a collection of reusable scripts tailored for WordPress development. It’s distributed as an npm package that seamlessly incorporates more advanced JavaScript tooling like code transpilation, linting, formatting, or testing. To set it up, you need to install it from npm with a single command:

npm install @wordpress/scripts --save-dev

It exposes an executable wp-scripts designed to be manually configured with the scripts section in the package.json file used in the Node.js project.

{
    "scripts": {
        "build": "wp-scripts build",
        "format:js": "wp-scripts format-js“,
        "lint:css": "wp-scripts lint-style",
        "lint:js": "wp-scripts lint-js",
        "start": "wp-scripts start"
    }
}

This example demonstrates the essential capabilities included. In most cases, it should be possible to accomplish all tasks using the recommended settings provided. There are more commands, and they also have support for customizations covering more advanced use cases.

Modern JavaScript

You might be now concerned that it’s too complex to integrate reusable blocks when using modern JavaScript for the WordPress block editor. I’m sure you will be happy to find out that the block scaffolding tool takes care of everything for you. By default, the command runs the interactive mode that lets you customize the block’s initial configuration.

npx @wordpress/create-block

The video below shows how it looks in action:

Block scaffolding with @wordpress/create-block package

The WordPress plugin’s generated structure includes support for the most popular JavaScript tools and ESNext or JSX syntaxes. Despite all the build step’s internal complexity, it is still ready to be activated in a WordPress installation with no further work.

Closing Thoughts

I hope that I convinced you to try the presented tools next time you develop for the WordPress block editor. I’m sure they will improve the onboarding experience since it’s only one command to run. It assists you in the process by asking key questions and makes all the decisions for you. The templates provided contain detailed code comments that link to all necessary resources. It’s also worth emphasizing that you don’t have to use all that I presented. Still, the recommended configuration exists to inspire you to discover what works best for you.

Finally, I recommend the WordPress team’s official tutorial that explains the ingredients necessary to create a custom block.


Comments

2 responses to “How to Start Block Development with Scaffolding”

  1. […] Ziółkowski published the tutorial “How to Start Block Development with Scaffolding” and walks you through the use of the official create-block script. The command line tool gets you […]

  2. […] How to Start Block Development with Scaffolding December 22, 2020 […]

%d