#Making sure there is only one static instance in library

1 messages · Page 1 of 1 (latest)

royal vault
#

Is there a way to ensure there is only one library/instance of npm package with typescript that has all the static methods?

#

from time to time im getting weird issues when some library tries to require two different versions of package, is there a way to force it via typescript/js or maybe in package.json?

river halo
#

what you are looking for is called package-lock.json

#

basically, when you install a dependency, npm computes the appropriate version (based on the other dependencies installed)

#

once it figured out what version to install, it downloads it and install it in the node_modules folder and writes that version in the package-lock.json

#

that way, when someone else wants to download your project to run it, npm knows what version to download, by simply reading the package-lock.json

#

this also guarantees version not to change over time

#

@royal vault

#

also it would maybe help if you showed the exact error message or the code
you should usually not have those kinds of errors

royal vault
#

that is not a problem

royal vault
river halo
#

hum, yes?

#

same thing in typescript

royal vault
#

however for some magical reason its possible when building typescript

#

i mean i know the reason, bundlers do change class name

river halo
#

they don't pick names that are already used

#

what's the error you're having exactly?

#

if any

royal vault
#

no error, i just need to make sure the same class does not exist

#

because if so, whole dependency injector falls apart

#

this is the package im having problems with https://www.npmjs.com/package/injector-next

river halo
#

DI isn't as big of a thing in JavaScript

#

it's not Java

#

class can change names during bundline or minification, be inlined, treeshaken, etc.

river halo
royal vault
#

and yet it works almost flawlessly unless for some odd reason there are 2 versions

river halo
#

the bundler will make sure the same name isn't used twice

river halo
royal vault
#

yes there is a problem

#

not error

#

having 2 instances means two "repos"

#

one cant access the other

#

and well, it just should never happen

#

so im either trying to throw an error when loading 2nd instance OR force yarn/npm to never have 2 versions

river halo
#

well, don't think you can do much to prevent that tbh

#

other than testig your services, etc.

#

the few places where you use the DI

royal vault
#

i was thinking of using some weird quicks like

#

(globalThis as any).__hasInjector

#

if (...) exist then throw error

river halo
#

I don't see how this would help

#

you define it once, then it will exist everywhere

#

and throw every single time

royal vault
#

no

#
if ((globalThis as any).__hasInjector) { throw Error(); }
(globalThis as any).__hasInjector = true;