Skip to content

Create Block: Create a more modular structure that is easier to extend to several blocks #25188

Description

@klinge

Is your feature request related to a problem? Please describe.
I've been struggling for days to set up a plugin that implements several blocks. I've looked at examples at github and around the net but most are outdated compared to newer block standards. I admit that my skills in using javascript/webpack/npm are fairly low.

Using the @wordpress/create-block script I quickly get a plugin with a single block up and running - but it's not easily extendable to several blocks. The php side of block init+setup is in the common "plugin.php" file. And when trying move stuff that is common to a block and place that in a subfolder to the src-folder I realize that the build/webpack scripts are not really supporting that.

What solution would you like
I would like the create-block script to generate a structure that is more modular and easier to extend to implementing more than a single block. Something like this:

plugin-folder
/build
/src
--/block1
----<all js, php, css-files that are unique to block1>
--/block2
----<all js, php, css-files that are unique to block2>
--/common-assets
----<files that are common between blocks - included js libraries, common styling etc>
plugin.php
package.json
..

Alternative solutions
The alternative would be to create as many plugins as you want blocks but this seems a bit unnecessary if creating several blocks.

Activity

  1. gziolo commented on Oct 24, 2020

    @gziolo
    Member

    The plan is to make it possible to build and use external templates for Create Block as proposed in #23712. When it's implemented it should be much easier to share alternative configurations that go beyond the setup optimized for Block Directory (https://wordpress.org/support/article/block-directory/) publishing.

  2. gziolo commented on Jan 9, 2021

    @gziolo
    Member

    @wordpress/create-block is one step closer to make it possible to support multiple blocks. It works now with custom templates published as npm packages. #27881 is a good example that is being explored that contains a variation of the single block from the block creation tutorial. Those templates can have any number of blocks but it isn’t possible to dynamically pick number of such blocks or collect individual input for all of them. It isn’t clear how far we want to customize the scaffolding tool in the near future. How do you envision interactive mode in CLI for the proposed plugin structure?

  3. skorasaurus commented on Jul 21, 2021

    @skorasaurus
    Member

    Been dealing with this on and off over the past couple months and @bosconian-dynamics has offered some solutions

    https://wordpress.stackexchange.com/questions/390282/possible-to-use-wordpress-create-block-with-multiple-blocks

  4. added
    [Type] New APINew API to be used by plugin developers or package users.
    and removed
    Needs DecisionNeeds a decision to be actionable or relevant
    on Sep 8, 2021
  5. gziolo commented on Sep 8, 2021

    @gziolo
    Member

    It looks like it is a recurring request from the community that I see more often these days. The most recent one happened on Twitter and was started by @cr0ybot:

    https://twitter.com/cr0ybot/status/1435379030522478596

    Struggling with folder structure for new WordPress Gutenberg features, esp. block.json. I want one plugin that handles multiple blocks, & each block has a folder with all relevant src files. So it contains index.js, block.json, style.css, and also index.php for dynamic blocks.

    This requires that we add support to @wordpress/create-block the capability to provide a CLI option to generate more than one block and based on that let users fill in details about multiple block. The other aspect is to settle on the folder structure used in the configuration with multiple blocks.

  6. changed the title [-]Let the create-block package create a more modular structure that is easier to extend to several blocks[/-] [+]Create Block: Create a more modular structure that is easier to extend to several blocks[/+] on Sep 8, 2021
  7. cr0ybot commented on Sep 8, 2021

    @cr0ybot
    Contributor

    To add to what @gziolo pulled in from my tweet, while I do believe that the standard create-block template should offer a best-practice approach for multiple blocks, the main thing I'm struggling with in this context is the location of the block.json file. It doesn't look like create-block currently creates a block.json in the template, but I assume it would put it in the root of the plugin following the current single-block approach.

    I prefer to have all files related to each "feature" grouped together in a single folder when possible. This works fine for JS+CSS only, but when you throw block.json in the mix you suddenly need a separate folder/location for the main block metadata. The funny thing is the Gutenberg block-library package is structured the way I want: all files for a block in one folder, including the block.json file. I haven't dug in to see how those metadata files are handled on compile—are they copied to another location?

  8. gziolo commented on Sep 8, 2021

    @gziolo
    Member

    It doesn't look like create-block currently creates a block.json in the template, but I assume it would put it in the root of the plugin following the current single-block approach.

    It creates block.json in the top-level directory and it's independent from the selected template. We can definitely iterate on that when multiple blocks are supported as it won't scale 😄

    I haven't dug in to see how those metadata files are handled on compile—are they copied to another location?

    Yes, they are copied (with webpack plugin) to the build folder:

    Screen Shot 2021-09-08 at 18 17 22

  9. cr0ybot commented on Sep 8, 2021

    @cr0ybot
    Contributor

    EDIT: This setup is currently not working. For some reason the renamed *.json files aren't playing nicely with register_block_type_from_metadata(). See additional comments below.

    EDIT: Code below updated to include "-block.json" at the end of the custom metadata filenames so that they are recognized by register_block_type_from_metadata(). The "-block" should not be needed after WordPress 5.9 is released, see https://core.trac.wordpress.org/ticket/53806.

    I've written up a quick webpack config for my project that moves the block.json file into the build folder. My plugin looks like this:

    build
    src
    ├ blocks
    │  ├ my-block
    │  │  ├ block.json
    │  │  ├ index.js
    │  │  └ style.scss
    │  └ my-other-block
    └ index.js
    package.json
    plugin.php
    webpack.config.js
    

    webpack.config.js

    const { basename, dirname } = require('path');
    
    const CopyWebpackPlugin = require('copy-webpack-plugin');
    const defaultConfig = require('@wordpress/scripts/config/webpack.config');
    
    module.exports = {
    	...defaultConfig,
    	plugins: [
    		...defaultConfig.plugins,
    		new CopyWebpackPlugin({
    			patterns: [
    				{
    					// Copy block.json to build folder with name of block as filename
    					from: 'src/blocks/**/block.json',
    					to({ absoluteFilename }) {
    						// Get the block folder name
    						const blockName = basename(dirname(absoluteFilename));
    						// Output with original extension (.json)
    						return `./${blockName}-block[ext]`;
    					},
    				},
    			],
    		}),
    	],
    };

    This copies the block.json file into the root of /build, so the relative paths within are as simple as possible:

    {
      ...
      "editorScript": "file:index.js",
      "style": "file:style-index.css"
    }

    EDIT: I've removed the preceding ./ from the relative paths above, they aren't needed and the client side URLs end up output that way.

    In plugin.php, each metadata file is fed to register_block_type().

    I do need to apologize because this is starting to feel a little off-topic from the initial purpose of this issue. Sorry about that. 😓

  10. gziolo commented on Sep 8, 2021

    @gziolo
    Member

    @cr0ybot, thank you for sharing more details. It is very helpful to plan future iterations.

    This copies the block.json file into the root of /build, so the relative paths within are as simple as possible:

    {
      ...
      "editorScript": "file:./index.js",
      "style": "file:./style-index.css"
    }

    I agree that colocating JS, CSS, and block.json in one build's subfolder makes everything so much simpler in terms of defining paths. The only downside is that you need to use CopyWebpackPlugin to ensure it all integrates nicely.

  11. ryanwelcher commented on Sep 8, 2021

    @ryanwelcher
    Contributor

    @gziolo @cr0ybot would it make sense to have an entry point for each block? If I am understanding the code here, it seems that all of the blocks are being combined into a single JS file. So in theory, calling the register_block_type for any block that uses the index.js file will register all the blocks on the client-side? This is probably fine in most cases, but might be worth calling out.

  12. cr0ybot commented on Sep 8, 2021

    @cr0ybot
    Contributor

    @ryanwelcher Yea sorry, I left that part out. The main /src/index.js file is importing each block folder's index.js file, which is where the actual registerBlockType() is located. But I don't believe that a single call to register_block_type() in PHP would pull all of them in, since as far as I understand it only registers a single block via a namespaced identifier or the path to a block.json metadata file. So the plugin.php file is running register_block_type() on each *.json file in the build folder, which in turn registers the script/style handles automatically for enqueuing.

    Here's where I've run into a weird hitch however, and I'm still determining if I've done something wrong: when I try using register_block_type() on these renamed block.json files (say, page-header.json), it isn't working. If I rename one back to block.json it works just fine? Looking at the source for register_block_type_from_metadata(), it looks like a differently-named json file should work just fine, no? I konw this isn't the place for troubleshooting but this is a huge hitch in my block.json relocating/renaming plan...

    EDIT: I just realized what you meant when you specified "client side". Yes, since the main index.js file should be enqueued, even if you only registered one block server-side, I see now that they would all be registered client side (only). Sorry!

  13. 44 remaining items

  14. stefanfisk commented on May 9, 2022

    @stefanfisk
    Contributor

    @cr0ybot Webpack supports sharing libraries between entrypoints if you use optimizations.runtimeChunk = 'single'. I've used it in several projects both for WordPress and random React stuff, and it works great as long as you have tooling to figure out which files need to be loaded.

  15. iamleese commented on Jul 13, 2022

    @iamleese

    It seems this issue has been resolved, for the most part. I was able to create multiple blocks using this method stated by @ryanwelcher.

    The block registrations in the .php file just needs to point to the correct build directory.

    function create_block_root_init() { register_block_type( __DIR__ . '/build/block-one' ); register_block_type( __DIR__ . '/build/block-two' ); }

    The documentation for @wordpress/create-block should be updated to reflect these changes since I pretty much wasted my time trying to modify the package.json with several start/build scripts.

  16. cr0ybot commented on Jul 18, 2022

    @cr0ybot
    Contributor

    @stefanfisk Oof, I should have looked into that a bit more before making a suggestion, thanks. Do you happen to know what kind of tooling would be required? Are you talking about WordPress script enqueuing or something else?

  17. stefanfisk commented on Jul 19, 2022

    @stefanfisk
    Contributor

    @cr0ybot Here's the code I was using at the time https://gist.github.com/stefanfisk/bb4e045f3d15829a377916dc5fee9acc

    I am no longer using this as my needs changed, so YMMV.

  18. gziolo commented on Aug 25, 2022

    @gziolo
    Member

    In the the last version published to npm you can find 2 new CLI options that should vastly improve the experience for extending existing projects with new blocks:

    --no-plugin

    With #41642 from @ryanwelcher, you can scaffold only the block folder with:

    npx @wordpress/create-block --no-plugin

    This way you can add as many blocks as you need to your project. You will only have to remember to wire them with:

    register_block_type( __DIR__ . '/build/path-to-block' );

    --variant

    With #41289 from @ryanwelcher, you can also pick different variants of the same block. By default, scaffolded blocks use the static form that contain the save method that produces HTML to store in the database and use on the front end. If you prefer to have more control over the output of the block, you can use , if template supports it, the dynamic block variant where save gets skipped and block gets rendered on the frontend with render_callback PHP implementation. This option can be passed with CLI command:

    npx @wordpress/create-block --variant dynamic

    or selected in the interactive mode.

  19. colorful-tones commented on Oct 5, 2022

    @colorful-tones
    Member

    I'm just catching up over here and wanted to point to #44717 which has a good deal of overlap here and I would love feedback from you folks. cc: @dgwyer @cr0ybot @illycz @gziolo Thanks!

  20. dgwyer commented on Oct 6, 2022

    @dgwyer
    Contributor

    @colorful-tones I created a wrapper CLI tool around create-block to extend it's capabilities. e.g. named blocks, and full Tailwind integration compiling CSS at the block level (separate files). I'd be open to adding more features. 🙂

    https://github.com/dgwyer/create-wp-block

  21. shoelaced commented on Nov 15, 2022

    @shoelaced

    Trying this and I'm getting messages like Skipping "./index.js" listed in "C:/path/to/plugin/src/block-a/block.json". File is located outside of the "src" directory and No entry file discovered in the "src" directory when trying to re-structure the folders as @ryanwelcher mentioned. Has this functionality changed? I'm on Windows, could there be something breaking #38781 from a while back?

  22. shoelaced commented on Nov 16, 2022

    @shoelaced

    Nevermind, I've figured it out and created an issue: #45792

  23. gziolo commented on Dec 3, 2024

    @gziolo
    Member

    I manage to handle multiple blocks. But multiple blocks do not work with --hot "Fast Refresh". It's through
    [HMR] Update failed: ChunkLoadError: Loading hot update chunk block-one/index failed. error.

    Regarding the issue reported by @amjadr360 in #25188 (comment). I have a proposal that addresses it for React components:

  24. gziolo commented on Aug 20, 2025

    @gziolo
    Member

    I’m not entirely sure if there is still anything actionable in this issue. It played it’s purpose as we were able to brainstorm and implement several enhancements for handling multiple blocks.

    Kudos to everyone involved! ❤️

    I opened a follow up issue with proposal for more enhancements and fixes:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Developer ExperienceIdeas about improving block and theme developer experience[Tool] Create Block/packages/create-block[Type] New APINew API to be used by plugin developers or package users.

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions