pile of brown wooden blocks

Using JavaScript modules in your WordPress plugins

Modules are nothing new in JavaScript programming, and it’s a good practice to modularize your code.

WordPress does not offer the option to load scripts as modules out of the box. There’s a ticket from mid 2022, but it hasn’t gained much traction yet. So we need a workaround for the time being.

Fortunately, WordPress provides a filter called “script_loader_tag”. Basically, it takes the <script> string generated by wp_enqueue_script and allows you to manipulate it. Without further ado, here’s the solution:

add_filter('script_loader_tag', function ($tag, $handle, $src) {
  $tag = str_replace('<script ', '<script type="module" ', $tag);
  return $tag;”
});

  • `$tag: the script tag generated by wp_enqueue_script
  • $handle: the script’s handle
  • $src: the script’s URL source

The filter takes the “<script” part of the tag and adds the necessary type=module part . That’s all.

In this context, the other interesting parameter is $handle. It allows you to include or exclude certain scripts from being manipulated, e.g.

add_filter('script_loader_tag', function ($tag, $handle, $src) {
   if ( 'NonModule.js' !== $handle ) {
      $tag = str_replace('<script ', '<script type="module" ', $tag);
   }”
   return $tag;
});