1

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?

2

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;

2
  • So, does this mean that, for example, I have to replace const { useSelect } = wp.data; with import { useSelect } from '@wordpress/data'; ?
    – leemon
    May 16 at 17:55
  • 2
    You have to add the import line at the top of your script, yes. You can still use wp.data in your script but you should replace that too because you can profit from code suggestions if you use VS Code or PHP Storm when you use the imported functions.
    – Edward
    May 16 at 18:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.