File structure and react setup when creating multiple Gutenberg blocks

Gutenberg-examples isn’t a single plugin, you can consider it five plugins at once, it is intended to be working example for each part of the tutorial.

You have a lot of patterns you can follow, currently, core blocks are defined each in a folder like this, coblocks also follows the same pattern.

block-library/
  - image/
    -- edit.js
    -- index.js
    -- save.js
    -- styles.css
  - quote/
    -- edit.js
    -- index.js
    -- save.js
    -- styles.css
  - index.js (root index)
  - styles.css (root style)

Each save.js & edit.js file contains the code for that function.

Each index.js for a block contains references to said files, plus some other settings like title & category

preformed code block index.js file example (simplified)

import edit from './edit';
import save from './save';

export const name="core/code";

export const settings = {
    title: 'Code',
    description: 'Display code snippets that respect your spacing and tabs.',
    category: 'formatting',
    icon: 'image',
    edit,
    save,
};

root styles.css just import each block style css.

root index.js file is the one responsible for calling & registering the blocks, so it goes something like this (simplified)

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

import * as image from './image';
import * as quote from './quote';
import * as code from './code';

const blocks = [
    image,
    quote,
    code
];

function registerBlock( block ) {
    const { name, setting } = block;
    registerBlockType( name, settings );
}

blocks.forEach( registerBlock );

or a larger example at coblocks

your plugin should call that index and register each block with the same file, just different block name.

see how coblocks does it

As for the build process, you don’t need node modules at each block, you just need to run it at the root index.js file.

For even a more simpler approach, you can use wp-scripts it’s used internally by gutenberg and also by gutenberg-examples, you install it at the root file of your plugin and add those scripts to your package.json

"scripts": {
    "build": "wp-scripts build",
    "start": "wp-scripts start"
}

it assumes that your code (root index.js) is in src/index.js and your output is at build/index.js (you can change that).

Leave a Comment