JavaScript ES modules: import and export explained
A theme’s JavaScript often starts as one file and grows into a tangle of global functions that overwrite each other. ES modules split code into files that declare what they offer (export) and what they need (import). Each module has its own scope, so nothing leaks into the global namespace, and build tools can drop code that is never imported.
Problem: A theme’s main.js has grown to two thousand lines of global functions, and adding a feature risks breaking another one with the same function name.
Solution: Split the code into modules with named and default exports, import what each file needs, and either bundle them with a build tool (webpack, @wordpress/scripts) or load the entry file in the browser with type="module".
Exporting
// utils.js: named exports
export function formatPrice( amount, currency = 'USD' ) {
return new Intl.NumberFormat( 'en-US', { style: 'currency', currency: currency } ).format( amount );
}
export function debounce( fn, delay ) {
let timer;
return function ( ...args ) {
clearTimeout( timer );
timer = setTimeout( () => fn.apply( this, args ), delay );
};
}
export const API_ROOT = '/wp-json/wp/v2';
// cart.js: one default export
import { formatPrice } from './utils.js';
export default class Cart {
constructor() {
this.items = [];
}
add( item ) {
this.items.push( item );
}
total() {
return formatPrice( this.items.reduce( ( sum, item ) => sum + item.price * item.qty, 0 ) );
}
}
Importing
// main.js: the entry point
import Cart from './cart.js';
import { debounce, API_ROOT } from './utils.js';
const cart = new Cart();
document.querySelector( '.search' )?.addEventListener( 'input', debounce( ( event ) => {
fetch( API_ROOT + '/posts?search=' + encodeURIComponent( event.target.value ) );
}, 300 ) );
Named exports are imported with their names in braces (and can be renamed: import { debounce as wait }); a default export gets any name you choose. In the browser, import paths must be full relative paths with the extension ('./utils.js'); bundlers also accept './utils'.
Loading modules in WordPress
The simplest way in a classic theme is a build step: @wordpress/scripts or webpack bundles all modules into one file, which is enqueued as usual. Without a build, the browser can load modules directly, if the script tag has type="module":
<?php
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_script( 'ha-main', get_template_directory_uri() . '/js/main.js', array(), '1.0', true );
} );
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if ( 'ha-main' === $handle ) {
$tag = str_replace( '<script ', '<script type="module" ', $tag );
}
return $tag;
}, 10, 2 );
The browser then loads cart.js and utils.js itself, following the imports. Modules are deferred automatically and run in strict mode. They cannot use globals defined with let/const in other scripts, but window.jQuery or data from wp_localize_script() are still available on window.
Update (2024): WordPress 6.5 added native support for script modules: wp_register_script_module() and wp_enqueue_script_module() print type="module" and an import map, so the script_loader_tag filter is no longer needed on 6.5+.
NOTE: Without a bundler, each imported file is a separate request. For a handful of modules over HTTP/2 that is fine; for dozens of small files, a build step that bundles and minifies them is faster for visitors.