Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add script as a module using wp_enqueue_script WordPress

I want to add a JavaScript module to a WordPress site. However by using wp_enqueue_script there is no option to set the type="module" in the <script> tag.

wp_enqueue_script( 'prodes-media-library-base', plugin_dir_url( __DIR__ ) . '/dist/js/classes/base.module.js', array(), '1.0' );

If I use the above to insert a script I cannot use import statement in my script.

like image 622
Red Avatar asked Feb 16 '26 12:02

Red


1 Answers

If your script execution depends on attributes:

Ref: https://developer.wordpress.org/reference/hooks/script_loader_tag/

add_filter( 'script_loader_tag', 'add_id_to_script', 10, 3 );

function add_id_to_script( $tag, $handle, $src ) {
  if ( 'dropbox.js' === $handle ) {
    $tag = '<script type="text/javascript" src="' . esc_url( $src ) . '" id="dropboxjs" data-app-key="MY_APP_KEY"></script>';
  }

  return $tag;
 }
like image 161
wbdlc Avatar answered Feb 18 '26 01:02

wbdlc