ES Modules in WordPress 6.5: wp_enqueue_script_module()

Script modules in WordPress: wp_enqueue_script_module()

For a long time, WordPress could only load classic scripts. Writing import and export in a theme meant a bundler, or a script_loader_tag filter that added type="module" by hand, with no way to share modules between plugins. WordPress 6.5 added the Script Modules API: modules are registered with an ID, WordPress prints an import map, and modules import each other by ID without a build step.

Problem: A theme’s front-end JavaScript is split into ES modules (a gallery, a filter, shared helpers). The theme loads them with wp_enqueue_script() plus a filter that rewrites the tag, every module repeats the full URL of the helpers, and the version query string of WordPress breaks the module cache between files.

Solution: Register the shared helpers with wp_register_script_module(), enqueue the entry modules with wp_enqueue_script_module() and declare the helper as a dependency, import it by its ID, load rarely used modules as dynamic dependencies, and pass data from PHP with the script_module_data_{$id} filter (WordPress 6.7+).

Register and enqueue

add_action( 'wp_enqueue_scripts', function (): void {
    $ver = wp_get_theme()->get( 'Version' );

    wp_register_script_module( 'ha/helpers', get_theme_file_uri( 'js/helpers.js' ), array(), $ver );

    wp_enqueue_script_module(
        'ha/gallery',
        get_theme_file_uri( 'js/gallery.js' ),
        array(
            'ha/helpers',
            array( 'id' => 'ha/lightbox', 'import' => 'dynamic' ),
        ),
        $ver
    );

    wp_register_script_module( 'ha/lightbox', get_theme_file_uri( 'js/lightbox.js' ), array( 'ha/helpers' ), $ver );
} );

WordPress prints an import map in the page that maps each registered ID to its URL with the version, and a <script type="module"> for each enqueued module. Static dependencies are also preloaded with <link rel="modulepreload">, so the browser downloads them in parallel instead of discovering them one by one. Dynamic dependencies are only in the import map: they are downloaded when the code imports them.

Import by ID

// js/gallery.js
import { qsa, onIdle } from 'ha/helpers';

qsa( '.ha-gallery img' ).forEach( ( img ) => {
    img.addEventListener( 'click', async () => {
        const { openLightbox } = await import( 'ha/lightbox' ); // loaded on the first click
        openLightbox( img.currentSrc, img.alt );
    } );
} );

onIdle( () => document.documentElement.classList.add( 'ha-gallery-ready' ) );
// js/helpers.js
export const qsa = ( selector, root = document ) => [ ...root.querySelectorAll( selector ) ];
export const onIdle = ( cb ) => ( 'requestIdleCallback' in window ? requestIdleCallback( cb ) : setTimeout( cb, 1 ) );

The bare specifier 'ha/helpers' works because of the import map: no relative paths, and another plugin could import the same module by its ID. Modules are deferred by nature and run in strict mode.

Pass data from PHP

Classic scripts get data with wp_localize_script() or wp_add_inline_script(); modules have no inline scripts. Since WordPress 6.7, data for a module is printed as JSON in a <script type="application/json"> tag:

add_filter( 'script_module_data_ha/gallery', function ( array $data ): array {
    $data['restUrl'] = esc_url_raw( rest_url( 'ha/v1/' ) );
    $data['labels']  = array( 'close' => __( 'Close', 'textdomain' ) );
    return $data;
} );
const config = JSON.parse( document.getElementById( 'wp-script-module-data-ha/gallery' )?.textContent ?? '{}' );

What modules cannot do (yet)

  • A script module cannot depend on a classic script (wp-api-fetch, jquery) through the dependency array. Classic globals like window.wp are still there if the classic script is enqueued separately, but the loading order is not guaranteed.
  • The block editor packages are classic scripts; modules are aimed at the front end. Core’s own modules are the Interactivity API (@wordpress/interactivity) and its router.
  • Modules of other code are removed by ID with wp_dequeue_script_module() or wp_deregister_script_module() (both 6.5), the same way as scripts.

Modules in the browser in general: ES modules, import and export. Blocks with viewScriptModule in block.json use the same API underneath: the Interactivity API.

NOTE: Import maps work in all current browsers since 2023 (Safari 16.4 was the last). The $ver argument ends up in the import map URL, so all imports of a module use the same versioned URL and the browser caches it once; that is the problem the manual approach had with WordPress’s ?ver= on only some of the files.