Enqueuing Block in WordPress Gutenberg

When developing Block for Gutenberg we start by enqueuing the JavaScript and CSS. There is two way to hook the enqueue block: enqueue_block_editor_assets and enqueue_block_assets.

The enqueue_block_editor_assets is used to enqueue the block only in the editor side of WordPress. This is used for main JavaScript Block and CSS that overrides the Block editor only styles.

/**
 * Enqueue block editor only JavaScript and CSS
 */
function sample_block_editor_scripts()
{

    $blockPath = '/assets/js/editor.blocks.js';
    $editorStylePath = '/assets/css/blocks.editor.css';

    wp_enqueue_script(
        'sample-blocks-js',
        plugins_url( $blockPath, __FILE__ ),
        [ 'wp-i18n', 'wp-element', 'wp-blocks', 'wp-components', 'wp-editor' ],
        filemtime( plugin_dir_path(__FILE__) . $blockPath )
    );

    wp_enqueue_style(
        'sample-blocks-editor-css',
        plugins_url( $editorStylePath, __FILE__),
        [],
        filemtime( plugin_dir_path( __FILE__ ) . $editorStylePath )
    );

}

add_action( 'enqueue_block_editor_assets', 'sample_block_editor_scripts' );

The enqueue_block_assets is used when the Block represent on how the Block be seen by the users. Gutenberg makes the close representation of Block in the editor and front-end a possibility. This is done by hooking the main Block CSS here.

/**
 * Enqueue front end and editor JavaScript and CSS
 */
function sample_block_scripts()
{
    $blockPath = '/assets/js/frontend.blocks.js';
    $stylePath = '/assets/css/blocks.style.css';

    wp_enqueue_script(
        'sample-blocks-frontend-js',
        plugins_url( $blockPath, __FILE__ ),
        [ 
          'wp-i18n', 'wp-element', 'wp-blocks',
          'wp-components', 'wp-api', 'wp-editor' 
        ],
        filemtime( plugin_dir_path(__FILE__) . $blockPath )
    );

    wp_enqueue_style(
        'sample-blocks-css',
        plugins_url($stylePath, __FILE__),
        null,
        filemtime(plugin_dir_path(__FILE__) . $stylePath )
    );

}

add_action('enqueue_block_assets', 'sample_block_scripts');

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.