I am following the "Store Post Meta with a Block" guide from the official Block Editor Handbook to add a custom post meta block using the supplied sample code (below). However, the block does not load and a Uncaught SyntaxError: Cannot use import statement outside a module
error is displayed from the myguten.js
file in the console when loading the block editor page.
How can I resolve this? Is the WordPress Block Editor Handbook code incorrect?
myguten-meta-block.php
:
// register custom meta tag field
function myguten_register_post_meta() {
register_post_meta( 'post', 'myguten_meta_block_field', array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
) );
}
add_action( 'init', 'myguten_register_post_meta' );
function myguten_enqueue() {
wp_enqueue_script(
'myguten-script',
plugins_url( 'myguten.js', __FILE__ ),
array( 'wp-blocks', 'wp-element', 'wp-components', 'wp-data', 'wp-core-data', 'wp-block-editor' )
);
}
add_action( 'enqueue_block_editor_assets', 'myguten_enqueue' );
myguten.js
:
import { registerBlockType } from '@wordpress/blocks';
import { TextControl } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { useEntityProp } from '@wordpress/core-data';
import { useBlockProps } from '@wordpress/block-editor';
registerBlockType( 'myguten/meta-block', {
title: 'Meta Block',
icon: 'smiley',
category: 'text',
edit( { setAttributes, attributes } ) {
const blockProps = useBlockProps();
const postType = useSelect(
( select ) => select( 'core/editor' ).getCurrentPostType(),
[]
);
const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );
const metaFieldValue = meta[ 'myguten_meta_block_field' ];
function updateMetaValue( newValue ) {
setMeta( { ...meta, myguten_meta_block_field: newValue } );
}
return (
<div { ...blockProps }>
<TextControl
label="Meta Block Field"
value={ metaFieldValue }
onChange={ updateMetaValue }
/>
</div>
);
},
// No information saved to the block
// Data is saved to post meta via the hook
save() {
return null;
},
} );