Question

I'm taking my first steps in Gutenberg block development and I'm already stuck. My block JS script makes use of a couple lodash functions (filter and pick). I'm registering my block using the following function:

function register_block() {
    wp_register_script(
        'block-script',
        plugins_url( 'block.build.js', __FILE__ ),
        array( 'wp-blocks', 'wp-components', 'wp-element', 'wp-utils', 'lodash' )
    );

    register_block_type( 'my/block', array(
        'editor_script' => 'block-script',
    ) );
}

As you can see I'm adding the lodash lib as a dependency, and checking the page source code it's effectively loaded before my plugin's script. However, I'm getting a ReferenceError: pick is not defined console error.

This is the line that calls the pick function:

onSelectImages( images ) {
    this.props.setAttributes( {
        images: images.map( ( image ) => pick( image, [ 'alt', 'caption', 'id', 'url' ] ) ),
    } );
}

I don't know what I'm doing wrong. Any ideas?

Thanks in advance

Was it helpful?

Solution

In the block script I had to replace:

import pick from 'lodash/pick';

with:

const { pick } = lodash;

And now it seems to work for me.

OTHER TIPS

The problem is that lodash isn't a script dependency, it's an NPM dependency:

array( 'wp-blocks', 'wp-components', 'wp-element', 'wp-utils', 'lodash' )

You can't enqueue it this way and expect your application to build. Lodash may be available in WP Admin, but webpack runs in a local Node CLI context, and it doesn't know what lodash is. So instead you need to use npm to acquire the library and include it in your final JS build via babel/webpack/etc. This way webpack/babel know about lodash and can do their job correctly.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top