Can't set values on `process.env` in client-side Javascript

柔情痞子 提交于 2020-07-23 06:38:15

问题


I have a system (it happens to be Gatsby, but I don't believe that's relevant to this question) which is using webpack DefinePlugin to attach some EnvironmentVariables to the global variable: process.env

I can read this just fine.

Unfortunatley, due to weirdnesses in the app startup proces, I need have chosen to do some brief overwritting of those EnvironmentVariables after the site loads. (Not interested in discussing whether that's the best option, in the context of this question. I know there are other options; I want to know whether this is possible)

But it doesn't work :(


If I try to do it explicitly:
process.env.myVar = 'foo';

Then I get ReferenceError: invalid assignment left-hand side.


If I do it by indexer (which appears to be what dotenv does) then it doesn't error, but also doesn't work:

console.log(process.env.myVar);
process.env['myVar'] = 'foo';
console.log(process.env.myVar);

will log undefined twice.


What am I doing wrong, and how do I fix this?

回答1:


The premise behind this attempted solution was flawed.

I was under the impression that webpack "made process.env.* available as an object in the browser".

It doesn't!

What it actually does is to transpile you code down into literals wherever you reference process.env. So what looks like fetch(process.env.MY_URL_VAR); isn't in fact referencing a variable, it's actually being transpiled down into fetch("http://theActualValue.com") at compile time.

That means that it's conceptually impossible to modify the values on the "process.env object", because there is not in fact an actual object, in the transpiled javascript.


This explains why the direct assignment gives a ref error (you tried to execute "someString" = "someOtherString";) but the indexer doesn't. (I assume that process.env gets compiled into some different literal, which technically supports an indexed setter)


The only solutions available would be to modify the webpack build process (not an option, though I will shortly raise a PR to make it possible :) ), use a different process for getting the Env.Vars into the frontEnd (sub-optimal for various other reasons) or to hack around with various bits of environment control that Gatsby provides to make it all kinda-sorta work (distasteful for yet other reasons).



来源:https://stackoverflow.com/questions/52871895/cant-set-values-on-process-env-in-client-side-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!