Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ES6 singleton pattern: module default exports an instance
class SingletonDefaultExportInstance {
constructor() {
this._type = 'SingletonDefaultExportInstance';
}
singletonMethod() {
return 'singletonMethod';
}
static staticMethod() {
return 'staticMethod';
}
get type() {
return this._type;
}
set type(value) {
this._type = value;
}
}
export default new SingletonDefaultExportInstance();
// ...
// index.js
import SingletonDefaultExportInstance from './SingletonDefaultExportInstance';
// Instantiate
// console.log(new SingletonDefaultExportInstance); // is not a constructor
// Prototype Method
console.log(SingletonDefaultExportInstance.type, SingletonDefaultExportInstance.singletonMethod());
// Getter/Setter
SingletonDefaultExportInstance.type = 'type updated';
console.log(SingletonDefaultExportInstance.type);
// Static method
console.log(SingletonDefaultExportInstance.constructor.staticMethod());
@bfintal

This comment has been minimized.

Copy link

commented Nov 5, 2017

As a named export:

export const singletonDefaultExportInstance = new SingletonDefaultExportInstance()

or if you want to export as the class' name:

const instance = new SingletonDefaultExportInstance()
export { instance as SingletonDefaultExportInstance }
@jasonkarns

This comment has been minimized.

Copy link

commented Nov 14, 2017

Be careful with this, because it's not a "true" singleton. It relies on the require cache for "singleton-ness", which isn't reliable.

For example, requiring the file above as require('./SingletonDefaultExportInstance') will result in a different instance of the module from require('./singletondefaultexportInstance') (assuming a case insensitive file-system).

@baltuonis

This comment has been minimized.

Copy link

commented Mar 9, 2018

@jasonkarns - so how do you export TRUE TRUE singleton?

@russelltrafford

This comment has been minimized.

Copy link

commented May 17, 2018

Yes, would be good to discuss :) Also for others coming across this later.

@sgnl

This comment has been minimized.

Copy link

commented Sep 27, 2018

IMHO, case insensitivity seems like it should be a bug with require's implementation if you're actually able to import a package that way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.