Inspired by @PaulNaveda, @peter and @zeldri
A small plugin demontrating JS modules support, including localization and inline scripts.
Content of wp-content/plugins/js-module-support-demo/js-module-support-demo.php
<?php
/*
Plugin Name: Javascript Module Support - Demo
Plugin URI: https://froger.me/
Description: Javascript Module Support - Demo
Version: 0.1
Author: Alexandre Froger
Author URI: https://froger.me/
*/
/* ---------------------------------------------------------------
* Below is the main logic - it can be used in plugins or a theme
* --------------------------------------------------------------- */
add_filter( 'script_loader_tag', 'add_type_attribute', 10, 3 );
function add_type_attribute( $tag, $handle, $src ) {
$type = wp_scripts()->get_data( $handle, 'type' );
if ( $type && is_string( $type ) ) {
$tag = str_replace( ' src=', 'type="' . esc_attr( $type ) . '" src=', $tag );
}
return $tag;
}
/* ---------------------------------------------------------------------------------------
* Below is the demo code - it adds the demo scripts (main, module, localization, inline)
* --------------------------------------------------------------------------------------- */
add_action( 'wp_enqueue_scripts', 'demo_scripts', 10, 1 );
function demo_scripts() {
$inline_script = '
console.log(\'this is an inline script added to demo.js\');
';
wp_enqueue_script( 'demo', plugin_dir_url( __FILE__ ) . 'js/demo.js', array(), false, true );
wp_scripts()->add_data( 'demo', 'type', 'module' );
wp_add_inline_script( 'demo', $inline_script );
wp_localize_script( 'demo', 'LocalizationVar', array( 'key' => 'value' ) );
}
Content of wp-content/plugins/js-module-support-demo/js/demo.js
import moduleVar from './module.js'
console.log(moduleVar);
console.log(window.LocalizationVar);
Content of wp-content/plugins/js-module-support-demo/js/module.js
const moduleVar = 'This is a variable from module.js';
export default moduleVar;
Upon execution of the full demo code, the following is seen in the console:
this is an inline script added to demo.js
This is a variable from module.js
{"key":"value"}