#2920 ES Environment Variables

SlimerDude Mon 17 Jun

Hi, While looking through the code for calling Fantom in JS / ES I've noticed some discrepancies.

WebOutStream.initJs() sets environment variables via globalThis.fan$env

// WebOutStream.initJs()

// init Env.vars to pickup in Env.$ctor
w("globalThis.fan\$env = {").nl

But in the same initJs(), when writing code for the new ES mode, the environment variables are still set manually.

// WebOutStream.initJs()

if (WebJsMode.cur.isEs)
  w("fan.sys.Env.cur().__loadVars(fan\$env);")

Could this be because es/Env.js is looking for js.fan$env and not globalThis.fan$env ?

// es/Env.js

constructor() {
  ...
  const vars = ((typeof js.fan$env) === 'undefined') ? {} : js.fan$env;
  this.__loadVars(vars);
}

I note that js/Env.js seems to look in the right global scope.

// js/Env.js

fan.sys.Env.prototype.$ctor = function() {

  if (typeof fan$env !== 'undefined'){
    // fan$env is used to seed Env.var; it must be defined before sys.js
    var keys = Object.keys(fan$env);
    ...
  }
}

My question therefore is - does es/Env.js need to be fixed up? (so WebOutStream.initJs() doesn't have to make a manual call to __loadVars())

(I'm also aware I may be missing some understanding of ES magic - as I'm not in a position where I'm able to use initJs() in anger.)

matthew Tue 18 Jun

Good catch Steve. Yeah that call to __loadVars() is redundant/unnecessary. The only requirement is that globalThis.fan$env is configured before loading sys.js.

SlimerDude Sun 23 Jun

Cool, but just to double check:

// es/Env.js

constructor() {
  ...
  const vars = ((typeof js.fan$env) === 'undefined') ? {} : js.fan$env;  // <-- this
  this.__loadVars(vars);
}

Is the js.fan$env correct, or should it be globalThis.fan$env?

(I've not come across the global js variable before.)

matthew Tue 25 Jun

Is the js.fan$env correct

Yes - if you look at sys/es/build.fan you will see in the init() method that when we write sys.js we have this line

printLine("const js = (typeof window !== 'undefined') ? window : globalThis;")

This defines js to be either window or globalThis depending on whether we are running in the browser or node. Probably this is unnecessary since I believe globalThis is equivalent to window in the browser. But as it stands it will work.

SlimerDude Tue 25 Jun

Ah, cool - I didn't see that. Thanks!

I believe globalThis is equivalent to window in the browser

Yeah, I believe so too.

Login or Signup to reply.