Implement a singleton with an ES module
Implement a singleton with an ES module in JavaScript: a module runs once, so its exports are one shared instance. Node.js 24.
You do not need a class with a static getInstance to get one shared object. A module is evaluated once, and everything that imports it gets the same exports.
console.log('logger created');
export const logger = {
lines: [],
log(message) {
this.lines.push(message);
},
};const first = await import('./logger.mjs');
const second = await import('./logger.mjs');
console.log(first.logger === second.logger);logger created
trueThe console.log at the top of logger.mjs runs once, on the first import, and the second import reuses the cached module. Both namespaces point at the same logger object, so state set through one is visible through the other. The behaviour is part of how modules are loaded in Node.js.
The cache is keyed by the full URL. ./logger.mjs?v=2 is a different module and runs again, and so is a copy of the file reached by another path, such as when two versions of a package are installed. Tests that need a fresh instance can use that on purpose.