Building custom blocks for WordPress. Blocks in WordPress are built in javascript (ES5, or ESNext/JSX then compiled down to js using webpack and bable). If you have used react or vuejs you will be very familiar with this workflow.

Install nodejs

First, you need to have node and npm setup on your system:

Linux: apt install nodejs npm
mac: brew install node
Windows: choco install node

Project init

I always start with git init, and add in a .gitignore:

git init

# ignore everything in the root except the "wp-content" directory.

# ignore everything in the "wp-content" directory, except:
# "mu-plugins", "plugins", "themes" directory

# ignore these plugins

# ignore specific themes

# ignore node dependency directories

# ignore log files and databases

Building custom blocks for WordPress – NPM

Next, you need to use npm to init your node project and add the wordpress test scripts:
create a working folder

mkdir blocks
cd blocks

npm init
# answer the questions
package name: (block) block
version: (0.0.01)
description: my block
entry point: (index.js) build/index.js
test command:
git repository:
author: myself
license: (ISC) closed, gpl, whatever -- see here

Next, install the wordpress test scripts in your project:

npm install --save-dev --save-exact @wordpress/scripts

Setup build scripts

Using the example from the wordpress developer docs, create a basic test block, at src/index.js

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

registerBlockType( 'jonathansblog/block', {
title: 'Basic Example',
icon: 'smiley',
category: 'design',
edit: () => "Hello, world!",
save: () => "Hello, world!",
} );

This will give us something to test with, but to create the actual javascript for the block, you have to build it:

Add the following configuration to the package.json scripts section:

"scripts": {
"build": "wp-scripts build",
"check-engines": "wp-scripts check-engines",
"check-licenses": "wp-scripts check-licenses",
"format:js": "wp-scripts format-js",
"lint:css": "wp-scripts lint-style",
"lint:js": "wp-scripts lint-js",
"lint:md:docs": "wp-scripts lint-md-docs",
"lint:md:js": "wp-scripts lint-md-js",
"lint:pkg-json": "wp-scripts lint-pkg-json",
"packages-update": "wp-scripts packages-update",
"start": "wp-scripts start",
"test:e2e": "wp-scripts test-e2e",
"test:unit": "wp-scripts test-unit-js"

Then you can build your custom WordPress blocks with the following

npm run build

You will now have built the javascripts needed or your wordpress custom blocks to run, but how do we load them into wordpress?

Building custom blocks for WordPress – Loading your block

In the root of the project, create a file called block.php (assuming your project is called ‘block’)

Add this info to the file (its generated by the build stage and contains the version info and dependencies for you):

Now you can commit to your git repo and load into a wordpress instance (or run ‘npm run start’ and start creating your blocks!)