block editor – Using wp_set_script_translations without manually registering the script

Question

When using wordpress user/create-block to scaffhold a plugin for a block, the generated bundle is automatically registered via the block.json metadata :

{
...
"name": "my-block",
"textdomain": "my-block",
"editorScript": "file:./index.js",
...
}


No need to call wp_register_script myself. This is great since it automatically handles dependencies via the index.asset.php file generated in the build folder.

Following the procedure mentionned in the doc, I then create a JET translation file. Here is the procedure :

1. Creating POT file with wp i18n make-pot . languages/my-block.pot
2. Creating PO file with cp languages/test.pot languages/my-block-FR_BE.po
3. Filling msgstr strings in my-block-FR_BE.po
4. Adding line "Language: fr_BE\n" to my-block-FR_BE.po
5. Creating JSON file with wp i18n make-json languages/my-block-FR_BE.po --no-purge

The JSON generated is appended with a md5 hash: my-block-fr_BE-cae574befd871d4f740fd8b719bac1db.json.

Now I have to call wp_set_script_translations in my init method :

function my_block_init() {
register_block_type( __DIR__ . '/build' );
wp_set_script_translations( 'my-block-script', 'my-block', plugin_dir_path( __FILE__ ) . 'languages/' );
}


This does not work.

In order to make it work, I have to register the script and enqueue it, loosing the ability to have dependencies automatically injected :

function my_block_init() {
wp_register_script(
'my-block-script',
plugins_url( __DIR__ . '/build/index.js', __FILE__ ),
array('react', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n', 'wp-react-refresh-runtime')
);
wp_enqueue_script('my-block-script');
register_block_type( __DIR__ . '/build' );

wp_set_script_translations('my-block-script', 'my-block', plugin_dir_path( __FILE__ ) . 'languages/');
}


I also need to rename my JSON file to include the script handle instead of the automatically generated md5 hash. The “Load Translation File” section in the doc gives me the impression that this shouldn’t be necessary when keeping the generated name, though I’m not sure of what I’m supposed to do here :

WordPress will check for a file in that path with the format ${domain}-${locale}-${handle}.json as the source of translations. Alternatively, instead of the registered handle you can use the md5 hash of the relative path of the file,${domain}-${locale} in the form of${domain}-${locale}-${md5}.json.

Is there a way to register JET translations for a script that is automatically registered via the block metadata ? And how can I use the generated name for the JSON file when registering my translation ?

0
1 month 2022-07-04T07:45:44-05:00 0 Answers 0 views 0