teleclimber
teleclimber3w ago

How to initialize global variable so it can be accessed without globalThis?

I'm hacking on a large existing codebase using Deno. This codebase uses a number of global variables like this:
if( __DEV__ && ... )
if( __DEV__ && ... )
Their build system sets these values at build time I think. I am trying to hack around without building, but I am stuck because I haven't figured out how to initialize these variables globally. I always get an error of "ReferenceError DEV is not defined". The code I'm working with uses ESM modules and TypeScript. There is a global.d.ts that sets
declare var __DEV__: boolean
declare var __DEV__: boolean
I include this global.d.ts via deno.json:
"compilerOptions": {
"types": [
"./global.d.ts"
]
},
"compilerOptions": {
"types": [
"./global.d.ts"
]
},
This makes the TS side of things happy. But I still don't know how to actually initialize that value. I tried globalThis, window, and just DEV = true; Any help would be appreciated, thanks!
4 Replies
teleclimber
teleclimberOP3w ago
I think I figured it out. Or at least I found a way to make it work, even if I don't understand why it works. I have to initialize the values in a separate file, using globalThis: And then import that file from my index.js entrypoint. globalThis.__DEV__ = true works from a file that is imported, but it doesn't work if I type the exact same thing in my index.ts. So I got it working, but if someone wants to explain enlighten me as to what's going on here I'm all ears.
marvinh.
marvinh.3w ago
When you do
if (__DEV__) {}
if (__DEV__) {}
then what's actually happening is
if (globalThis.__DEV__) {}
if (globalThis.__DEV__) {}
In other words: All global variables hang off of the globalThis object. That's the object that holds the global scope.
teleclimber
teleclimberOP3w ago
OK but that doesn't explain why doing globalThis.__DEV__ = true from the main script has no effect.
marvinh.
marvinh.3w ago
Where are you putting that line? Are you putting it before or after imports of other modules?

Did you find this page helpful?