(function() {
var id_counter = 1;
Object.defineProperty(Object.prototype, "__uniqueId", {
writable: true
});
Object.defineProperty(Object.prototype, "uniqueId", {
get: function() {
if (this.__uniqueId == undefined)
this.__uniqueId = id_counter++;
return this.__uniqueId;
}
});
}());
#How do I run a piece of code once at startup?
25 messages · Page 1 of 1 (latest)
If I were to use this code in my project, I would want it to run once and only once at startup
How do you design a typescript project to do run a snippet like the above in such a way?
Let me know if I'm not providing enough information. I don't know if the answer depends on the environment. My code will run in node.js, but I'm looking for a general-purpose answer if one exists.
If I couldn't ask, here's how I would do it:
- Put this code in a file
- Import that file at the top of
index.ts(or whatever file is the main entry point).
i'm not sure if the __unique_id is supposed to be the actual use of the function or attempting "one run only" or what
if it's the latter, i'd be attaching symbols to globalThis, but preferably not doing that at all and just importing the file normally
iirc both cjs and esm have caching so a repeated import doesn't rerun top-level code of that module
neither, it's just the code I would want to run once at startup. You can completely ignore it. I thought it would help to show a real use case
basically, the code that is the body of a module that's statically imported is already run once and only once at startup
dynamic imports can be subject to logic/control flow, and they might be executed after initial loading (after startup)
with esm, that would be import vs import(), although if the latter is run in the body of a module then that's also done once on startup
with cjs, it's only really based on where the call is, since both cases would still use require
Okay thanks. I had never heard the term "static import," but that's what I thought it meant
i think it wasn't as concretely defined before esm was a thing
As far as I can tell, you are telling me to do this
yes
Okay that would work, but my main question is, is that idiomatic?
what you're asking doesn't really sound like it's a niche case. all initialization code is intended for "once and only once at startup"
why wouldn't it be? it's basically the bare description of what a module system does
i mean not even the module system, all top-level code is really only ever run once in basically every environment and language
I assumed it's not idiomatic to have side effects on import, but I didn't know another way to achieve this