ES6 modules give JavaScript a native module system. Before them, the ecosystem relied on CommonJS (Node.js) or AMD (RequireJS). Native modules use import and export syntax, work in modern browsers, and are the foundation of every modern build tool — Webpack, Rollup, Parcel.
Problem: How do you split JavaScript code into reusable modules with proper import/export syntax instead of relying on globals or script concatenation?
Solution: Use ES6 module syntax — export named exports or a default export from each file, then import only what you need in the consuming file. Bundle with webpack or Vite for broad browser compatibility.
Named exports and imports:
// utils.js
export function formatDate( date ) {
return new Date( date ).toLocaleDateString( 'en-GB' );
}
export function slugify( text ) {
return text.toLowerCase().replace( /\s+/g, '-' ).replace( /[^\w-]/g, '' );
}
export const VERSION = '1.0.0';
// main.js
import { formatDate, slugify, VERSION } from './utils.js';
console.log( formatDate( new Date() ) );
console.log( slugify( 'Hello World' ) ); // 'hello-world'
Default export — one per file:
// api.js
export default class Api {
constructor( baseUrl ) {
this.baseUrl = baseUrl;
}
async get( endpoint ) {
const res = await fetch( this.baseUrl + endpoint );
return res.json();
}
}
// main.js — default import can use any name
import Api from './api.js';
const api = new Api( 'https://example.com/wp-json/wp/v2' );
api.get( '/posts' ).then( posts => console.log( posts ) );
Using modules in WordPress themes with Webpack:
// webpack.config.js (simplified)
module.exports = {
entry: './src/js/main.js',
output: {
filename: 'bundle.js',
path: __dirname + '/dist',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader', // transpile for older browsers
},
],
},
};
NOTE: Native ES modules in the browser require <script type="module"> and an HTTP server (they don't work via file://). For WordPress themes, a build tool like Webpack is more practical — it bundles modules into a single file, handles transpilation, and produces a single enqueue-able asset.