You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Create Block: Create a more modular structure that is easier to extend to several blocks #25188
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.
Reacted by Will Skora, Ross Morsali, Anoop, Greg Ziółkowski, Elijah, Adam Biggs, Daniel Grossfeld, lauregch, SEO Themes, DanielVierheilig and 3 more
Reacted by Will Skora, Elijah, Daniel Grossfeld and Karsten Gresch
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.
@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?
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:
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.
Reacted by Eh Jewel, Adam Bosco and Karsten Gresch
Reacted by Cory Hughart, Ross Morsali, Adam Bosco and Karsten Gresch
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
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?
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:
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:
const{ basename, dirname }=require('path');constCopyWebpackPlugin=require('copy-webpack-plugin');constdefaultConfig=require('@wordpress/scripts/config/webpack.config');module.exports={
...defaultConfig,plugins: [
...defaultConfig.plugins,newCopyWebpackPlugin({patterns: [{// Copy block.json to build folder with name of block as filenamefrom: 'src/blocks/**/block.json',to({ absoluteFilename }){// Get the block folder nameconstblockName=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:
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.
@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.
@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!
@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.
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.
@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?
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:
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.
Reacted by Eric Davis, Scott Kingsley Clark and Karsten Gresch
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!
@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. 🙂
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?
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:
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:
Activity
gziolo commentedon Oct 24, 2020
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.
gziolo commentedon Jan 9, 2021
@wordpress/create-blockis 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?skorasaurus commentedon Jul 21, 2021
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
gziolo commentedon Sep 8, 2021
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
This requires that we add support to
@wordpress/create-blockthe 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.[-]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[/+]cr0ybot commentedon Sep 8, 2021
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?
gziolo commentedon Sep 8, 2021
It creates
block.jsonin 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 😄Yes, they are copied (with webpack plugin) to the
buildfolder:cr0ybot commentedon Sep 8, 2021
EDIT: This setup is currently not working. For some reason the renamed *.json files aren't playing nicely withregister_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:
webpack.config.js
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 toregister_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. 😓
gziolo commentedon Sep 8, 2021
@cr0ybot, thank you for sharing more details. It is very helpful to plan future iterations.
I agree that colocating JS, CSS, and
block.jsonin onebuild's subfolder makes everything so much simpler in terms of defining paths. The only downside is that you need to useCopyWebpackPluginto ensure it all integrates nicely.ryanwelcher commentedon Sep 8, 2021
@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_typefor any block that uses theindex.jsfile will register all the blocks on the client-side? This is probably fine in most cases, but might be worth calling out.cr0ybot commentedon Sep 8, 2021
@ryanwelcher Yea sorry, I left that part out. The main
/src/index.jsfile is importing each block folder'sindex.jsfile, which is where the actualregisterBlockType()is located.But I don't believe that a single call to. So theregister_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 ablock.jsonmetadata fileplugin.phpfile is runningregister_block_type()on each*.jsonfile 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 renamedblock.jsonfiles (say,page-header.json), it isn't working. If I rename one back toblock.jsonit works just fine? Looking at the source forregister_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 myblock.jsonrelocating/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!
44 remaining items
stefanfisk commentedon May 9, 2022
@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.iamleese commentedon Jul 13, 2022
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.
cr0ybot commentedon Jul 18, 2022
@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?
stefanfisk commentedon Jul 19, 2022
@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.
gziolo commentedon Aug 25, 2022
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-pluginWith #41642 from @ryanwelcher, you can scaffold only the block folder with:
This way you can add as many blocks as you need to your project. You will only have to remember to wire them with:
--variantWith #41289 from @ryanwelcher, you can also pick different variants of the same block. By default, scaffolded blocks use the static form that contain the
savemethod 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 wheresavegets skipped and block gets rendered on the frontend withrender_callbackPHP implementation. This option can be passed with CLI command:or selected in the interactive mode.
colorful-tones commentedon Oct 5, 2022
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!
dgwyer commentedon Oct 6, 2022
@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
shoelaced commentedon Nov 15, 2022
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" directoryandNo entry file discovered in the "src" directorywhen 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?shoelaced commentedon Nov 16, 2022
Nevermind, I've figured it out and created an issue: #45792
gziolo commentedon Dec 3, 2024
Regarding the issue reported by @amjadr360 in #25188 (comment). I have a proposal that addresses it for React components:
gziolo commentedon Aug 20, 2025
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: