Actually, you do not need to worry about adding the Masonry’s script handle to the dependencies
array in the asset file (index.asset.php
).
All you needed to do to make your Masonry code work properly is by using the script
property to add the masonry
(and imagesloaded
) as dependencies for your editor and view/front-end scripts.
"editorScript": "file:./index.js",
"script": [
"imagesloaded",
"masonry"
],
"viewScript": "file:./view.js",
I don’t know and haven’t checked further why adding the above (trick) worked well for me.masonry
to the editorScript
and viewScript
did not work, but
- Using the
script
property to add the dependency, is also the reason why the Gutenberg Test Iframed Masonry Block worked. I.e. The plugin manually registered the shared editor and front-end script, and the plugin also sets"script": "iframed-masonry-block-script"
in the block metadata.
For completeness though, I created a simple Webpack plugin which basically modifies the asset source before it is written to the asset file, but (hopefully) after the Dependency Extraction Webpack Plugin added the asset to the compilation queue.
Here’s the plugin which I placed it in the root project folder.
And here’s my custom Webpack config file, i.e. webpack.config.js
.
BTW, thanks for sharing about the Gutenberg Test Iframed Masonry Block. 🙂 Happy coding!
Update 21 Feb 2024
Regarding the strikethrough text above:
-
Scripts (and styles) in the editor canvas are enqueued via
_wp_get_iframed_editor_assets()
which runsadd_filter( 'should_load_block_editor_scripts_and_styles', '__return_false' )
and thendo_action( 'enqueue_block_assets' )
. ( see source on GitHub ) -
wp_enqueue_registered_block_scripts_and_styles()
is then called because it is hooked on theenqueue_block_assets
action. -
So the reason why Masonry was not loaded in the editor canvas is because the above function will only enqueue editor assets if
wp_should_load_block_editor_scripts_and_styles()
(which applies the above filter) returns true.That is understandable, though. However, that function also never enqueues the view/front-end-only scripts!
More specifically, if you look at the source, the function should have also enqueued the scripts in the
view_script_handles
property, i.e.$block_type->view_script_handles
.I have no idea why are they not being enqueued? 🤔 Perhaps, as you commented, “This might be a bug because it makes no sense“..