Using JavaScript modules in your WordPress plugins

pile of brown wooden blocks

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;
});

Your post must include a link to this post.

How does this work?
Write a response on your own website and include a link to this post. Then submit your response’s URL here. Your response may appear here after moderation. To update or remove it, edit or delete your original post and submit the same URL again. Learn more about Webmentions.