When we enqueue a script, the resulting HTML link tag’s ID attribute is the script’s registration handle with “-js” appended. Look through a page’s source HTML code for something similar for your hwscript.js file. It may not be the same for block scripts, but if it is, you can deduce the original registration handle.
Rather hacky, but you could bypass the usual localization process and directly output the script assignments you need within an inline <script> block from the ‘wp_print_scripts’ action hook.
Disclaimer: there may be a “right” way to do this that I’m unaware of, but one of these two should work for you, if not entirely “proper”.
Hi bcworkz,
You are right, I found the handle through the id attribute of the HTML tag. I was downright convinced that the value in the second element of the “viewScript” array was the handle of the script, so what is supposed to be that string?
Thanks
Good question! I have no idea, sorry. After a bit of research, I think it’s an alternative way of referencing a script that is already registered. With
"viewScript": [
"file:./hwscript.js",
"hbw-words-script"
],
you’re saying enqueue both hwscript.js and the script registered as “hbw-words-script”. It’s not a handle for your file, it’s a handle of some other file to be enqueued as well. If such a registration does not exist, it’s probably ignored.
I decided this is the case from https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#wpdefinedasset
I think you are right. Anyway, the documentation is not clear about this. I managed to use wp_localize_script with the handle I found on the HTML script tag.
Thanks
Thanks @bcworkz. I know it’s not recommended but I went with
if (!empty($this->data)) {
wp_localize_script('blocknamespace-' . $this->name. '-editor-script', $this->name, $this->data);
}
And it works like a charm.