Can the index.asset.php file be used with the enqueue_block_editor_assets action?
-
20-05-2021 - |
Frage
I'm developing a plugin that registers a PluginDocumentSettingPanel
in Gutenberg. As this is not a block, I cannot use the register_block_type
function to add its assets, so I have to employ the enqueue_block_editor_assets
action in its place.
function my_enqueue_block_editor_assets() {
$dir = dirname( __FILE__ );
$script_asset_path = "$dir/build/index.asset.php";
if ( ! file_exists( $script_asset_path ) ) {
throw new Error(
'You need to run `npm start` or `npm run build` for the block first.'
);
}
$script_asset = require( $script_asset_path );
wp_enqueue_script(
'my-gutenberg-plugin',
plugins_url( 'build/index.js', __FILE__ ),
$script_asset['dependencies'],
filemtime( plugin_dir_path( __FILE__ ) . 'build/index.js' )
);
}
add_action( 'enqueue_block_editor_assets', 'my_enqueue_block_editor_assets' );
But, using this approach it seems that I cannot use the generated index.asset.php
file to load the script dependencies, as I'm getting multiple wp.editor is undefined
/ wp.coreData is undefined
/ etc... errors.
If I explicitly state ALL the script dependencies using array( 'wp-editor', 'wp-data', etc... )
, there are no errors.
Is there a way to use the index.asset.php
file with enqueue_block_editor_assets
? If so, how?
Lösung
Yes you can use the index.asset.php file in the 'enqueue_block_editor_assets' action. I guess you missed to npm install the dependencies you want to use and import them in your script. That's how @wordpress/scripts generates your asset.php file. If you do not import the dependencies in your JavaScript files the dependency management of asset.php wont work.
For example:
npm install @wordpress/api-fetch --save
In your script:
import apiFetch from '@wordpress/api-fetch;
For more information have a look here: https://medium.com/write-better-wordpress-code/properly-add-modern-javascript-to-gutenberg-14bde8679d83