@m9ch/make-class-singleton
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

@m9ch/make-class-singleton

npm version npm downloads

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-singleton

Usage

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) // true

Use as ClassDecorator

[!NOTE] If using TypeScript, you might need to enable compilerOptions.experimentalDecorators in tsconfig.json or 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) // true

Options

  • container: Where singleton instance should create and stored, default is a WeakMap object 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 WeakMap object may save (not verified).

License

MIT © Mitscherlich

Readme

Keywords

none

Package Sidebar

Install

npm i @m9ch/make-class-singleton

Weekly Downloads

1

Version

0.1.0

License

MIT

Unpacked Size

9.45 kB

Total Files

9

Last publish

Collaborators

  • mitscherlich36