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');