On this topic, also support for inline & external module scripts. Just sharing the below, to see if anyone tried something similar, and have any suggestions.
Probably there are better solutions… meanwhile, pg-wp-addon, if it sets the information that the script is of type=“module” (can be extended to async, defer, once, nonce etc) in the script’s id
(which currently is of format inline-script-x
), then the id
can be used by wp_inline_script_attributes
&& wp_script_attributes
hooks to set the script tag as type="module"
.
For eg, (assuming assets
are available within the public
folder of the theme),
Flavour-1 - Module script imported using src
<script type="module" src="/assets/my-module.js"></script>
If this is generated…
wp_register_script('inline-module-script-1', "/assets/my-module.js", [], '1.0.0', true);
wp_enqueue_script('inline-module-script-1');
wp_scripts()->add_data('inline-module-script-1', 'type', 'module');
Flavour-2 - Module script where the import is within the script body (alternative to flavour-1)
<script type="module">
import {something} from "/assets/my-module.js";
something();
</script>
If this is generated…
wp_register_script('inline-module-script-1', '', [], '1.0.0', true);
wp_enqueue_script('inline-module-script-1');
wp_add_inline_script('inline-module-script-1', 'import {something} from "/assets/my-module.js";something();');
Then, we could use these two hooks to set the type="module"
attribute like this (added to inc/custom.php
):
<?php
/*
Use this file to add custom PHP code to your theme or plugin
*/
add_filter('wp_inline_script_attributes', 'add_type_module_attribute');
add_filter('wp_script_attributes', 'add_type_module_attribute');
function add_type_module_attribute($attributes)
{
if (isset($attributes['id']) && str_contains($attributes['id'], '-module')) {
$attributes = array_merge($attributes, array('type' => 'module'));
}
return $attributes;
}
?>
Some related info, for any solution involving wp_scripts()->add_data('inline-script-1', 'type', 'module');
which probably won’t work for inline scripts