@m9ch/make-class-singleton
v0.1.0
Published
Convert ES-Class into Singleton
Downloads
3
Readme
@m9ch/make-class-singleton
Install
via pnpm, yarn or npm:
pnpm add @m9ch/make-class-singleton
# or
yarn add @m9ch/make-class-singleton
# or
npm i -S @m9ch/make-class-singletonUsage
Use as factory function:
import { Singleton as makeSingleton } from '@m9ch/make-class-singleton'
class Foo {}
const Singleton = makeSingleton(Foo)
const foo = new Singleton()
const bar = new Singleton()
console.log(foo === bar) // trueUse as ClassDecorator
[!NOTE] If using
TypeScript, you might need to enablecompilerOptions.experimentalDecoratorsintsconfig.jsonor something like that.Here is an example:
{ "compilerOptions": { "target": "esnext", "module": "esnext", "modeResolution": "node", "experimentalDecorators": true } }
import { Singleton } from '@m9ch/make-class-singleton'
@Singleton
class Foo {}
const foo = new Foo()
const bar = new Foo()
console.log(foo === bar) // trueOptions
container: Where singleton instance should create and stored, default is aWeakMapobject in this module.
[!Note] It might be unsafe if using default instance container in multi-thread environment, such as nodejs in swarm mode, or
WebWorker.By passing a thread shared
WeakMapobject may save (not verified).
License
MIT © Mitscherlich
