16th March 2019 in Wordpress

Create your own Gutenberg Boilerplate – Part 1

The first thing when we need to start building Gutenberg Blocks is setting up few tools properly. It’s a good idea if we build a Boilerplate where we have all initial setup ready, this saves a lot of time while starting a new project.

Also building your own Boilerplate gives you complete control on what tools and setup you are using with the ability to update or change it with time (as needed).

These acricles will also cover all the basics you need to learn in order to start building your own Gutenberg Blocks.

While It’s possible to create Gutenberg blocks without using tools like Webpack and Node, and with ES5 (old version of JavaScrip), I am going to use all the modern tooling and ES6 syntax so that out boilerplate is future ready.

You can use create-guten-block to build your boilerplate quickly and (maybe) more effectively. These articles however, will help you understand what create-guten-block is doing for you under the hood.

Competed Code for reference. 

You can download the code from github repository:
https://github.com/hsrtech/gutenberg-block-boilerplate

You can refer to the code on github in case you run into any error while trying the code that I have used in this article.

Let’s get started… 

Step 1: Setup a new Plugin

If you are new to WordPress Plugin development, you can read about it in the Plugin Handbook provided by WordPress. 

Gutenberg Blocks are created as plugins. So the first thing we need to do is create a new folder in our /wp-content/plugins/ folder. Let’s name our folder as gutenberg-boilerplate.

Next, create a file gutenberg-boilerplate.php in the folder and define our plugin.

<?php
/**
 * Plugin Name: Gutenberg Boilerplate
 * Description: This is a Boilerplate plugin to start building Gutenberg Blocks.
 * Text Domain: gutenberg_boilerplate
 * Version: 1.0.0
 **/

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) { exit; }

// Block Initializer.
require_once plugin_dir_path( __FILE__ ) . 'blocks/init.php';

That’s all we need to add in this file.

  1. First we are defining our plugin in the comments (Plugin Header), this is the information that WordPress displays about our plugin on the Plugins page. You can add more information, however only Plugin Name is required and rest of the information is optional. You can read more about Plugin Header here
  2. Next, we are adding little security measure so that our PHP file can not be accessed directly from URL or another unidentified sources.
  3. Last, we are including a file. We will create this file in next steps and use this to register our block and all Scripts and CSS files related to our block.

You can see that our Plugin is now available in the list of Plugins in WordPress Admin. If you feel tempted to activate the plugin, you will first need to comment out the last line in the PHP file that we have created, because we are including a file that we have not created yet, and this will produce an error.

Step 2: Prepare Tools – Node, Webpack, Babel…

Let’s start with setting up a minimum configuration that we need to start building Gutenberg Blocks; we will add more features to our boilerplate toolset later.

With Webpack we can do a lot of things, like adding babel support, SCSS compilation, minification and uglification of our JS and CSS files. All this stuff is really useful to make our code fast and secure, and helps us in development by providing additional features. 

Create a new file named blocks.js

Before we start, create a folder named blocks and add an empty file named blocks.js. This file works as a single entry point for all our blocks. We will touch this file in a later step.

It will be structured like this: /wp-content/plugins/gutenberg-boilerplate/blocks/blocks.js

Install Node.js

First tool we need is Node JS. If you don’t have Node installed already on your computer, you can go to Node.js download page, download the installable file there, and follow the installation instructions on their website. 

Create package.json file

Assuming that you have downloaded and installed the node js, let’s create package.json file now. This file will maintain a list of all the node packages we need for our Gutenberg Block. In addition, we will add some commands in this file to create our build process.

In your plugin’s root folder /wp-content/plugins/gutenberg-boilerplate, create a new file named package.json, and add the following code in it:

{
  "name": "gutenberg-boilerplate",
  "version": "1.0.0",
  "private": true,
}

I am not creating this file using npm init because we do not need any other information added in this file about our project. However you can add more information as needed for your projects. 

You can read more about package.json file in the official documentation here, and update the file to match your needs. 

Install necessary modules/packgages

Next we need to install few modules using NPM 

Run following command on your command prompt to install all these modules in our plugin’s folder:

npm install --save-dev --save-exact webpack webpack-cli babel-loader @babel/core @babel/plugin-transform-react-jsx cross-env

Updated package.json file after installing all modules:

{
  "name": "gutenberg-boilerplate",
  "version": "1.0.0",
  "private": true,
  "devDependencies": {
    "@babel/core": "7.3.4",
    "@babel/plugin-transform-react-jsx": "7.3.0",
    "babel-loader": "8.0.5",
    "cross-env": "5.2.0",
    "webpack": "4.29.6",
    "webpack-cli": "3.2.3"
  }
}

You will also see a new folder named node_modules. This folder contains all the modules that we have installed above.

When distributing your plugin you don’t need to include “node_modules” folder in it. You can reinstall all modules by using command npm install. This command will create node_modules folder for you and install all modules listed in package.json file.

Preparing Webpack & Babel

Now after installing all necessary packages, we need to create a file that will hold all the configuration needed for webpack to work according to our requirements. 

Create a new file webpack.config.js.
Add the following code to this file:

// sets mode webpack runs under
const NODE_ENV = process.env.NODE_ENV || 'development';
const path = require('path');

module.exports = {
    mode: NODE_ENV,
    // entry is the source script
    entry: './blocks/blocks.js',
    // output is where to write the built file
    output: {
        path: path.join( __dirname, 'dist'),
        filename: 'blocks.build.js',
    },
    module: {
        // the list of rules used to process files
        // this looks for .js files, exclude files
        // in node_modules directory, and uses the
        // babel-loader to process
        rules: [
            {
                test: /.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',
            },
        ],
    },
};

Here we are giving instructions to webpack to read our /blocks/blocks.js file, compile it using babel (and exclude the files in node_modules folder in the process). And to save the output in /dist/blocks.build.js file. Webpack will automatically create this folder and file for us.

Next we need to create a file named .babelrc to add some configuration for babel

{
    "plugins": [
        [ "@babel/plugin-transform-react-jsx", {
            "pragma": "wp.element.createElement"
        } ]
    ]
}

Here we are instructing babel to transform JSX code using wp.element.createElement() function instead of React.createElement() which is default behaviour of transform-react-jsx plugin. 

If you are interested you can read more about wp.element.createElement here in Gutenberg documentation. 

Configure npm to run webpack

We are almost there, last thing we need to do is add few lines in package.json file for setting up our commands that will run babel. 

Add a scripts section in package.json file with following code. 

"scripts": {
    "dev": "webpack --watch",
    "build": "cross-env NODE_ENV=production webpack"
},

Here we have created two different commands for development and production modes. 

You can run npm run dev on your command prompt, it will start webpack with a –watch flag. webpack will process our blocks.js file and it keeps watching for any changes until you manually kill the process using ctr+c.

The second command we have created is num run build. This will prepare a production ready, minified version of our blocks.js file.

You can go ahead and test both commands, they will create a folder named dist with a blocks.build.js file in it. 

Here’s our complete package.json file with all code we have added so far:

{
  "name": "gutenberg-boilerplate",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "webpack --watch",
    "build": "cross-env NODE_ENV=production webpack"
  },
  "devDependencies": {
    "@babel/core": "7.3.4",
    "@babel/plugin-transform-react-jsx": "7.3.0",
    "babel-loader": "8.0.5",
    "cross-env": "5.2.0",
    "webpack": "4.29.6",
    "webpack-cli": "3.2.3"
  }
}

We have our webpack and babel setup ready. In the next part we will register our block and enqueue the scripts and CSS files related to it. 

About the author

Alok Jain

Alok design digital experiences to help businesses achieve their goals. He is passionate about designing right User Experience for their customers. For over 15 years, he have worked with small startups to mature product teams. Whether it is designing a WordPress product, a frontend experience, WooCommerce, Shopify, he follow the best product development practices for design and code, for desktop or mobile.