nx-remotecache-custom
nx-remotecache-custom copied to clipboard
Loading dotenv prevents nx from properly layering env files
Hi,
NX has the feature of allowing developers to create .env files specific to different targets and configurations: https://nx.dev/recipes/environment-variables/define-environment-variables
E.g. having a baseline .env file and .env.serve with overrides
Under the hood, they parse each file and layer them according to the rules mentioned in the docs, and then override those with process.env, e.g.
// Start With Dotenv Variables
...this.getDotenvVariablesForTask(task),
// User Process Env Variables override Dotenv Variables
...process.env,
Which makes sense, since user provided environment variables should override environment files.
The issues is, this library uses dotenv to parse and configure relevant variables from .env file, during which this line is executed:
if (!processEnv[key]) {
processEnv[key] = parsed[key]
}
This means that process.env is populated by dotenv with the values from .env if they aren't already present, which prevents NX from properly layering the environment files, because process.env will always override everything with the values from .env (the code from this library is executed earlier than NX's internal loading code).
My suggestion would be to read the .env file manually and parse it using dotenv.parse(dotenvFileContent) instead of calling dotenv.config().
For us, since we're not using dotenv, we disabled this option anyway.
Ah interesting, I might have missed that during one of the upgrade. I'll see if I maybe can use the dotenv parser from NX directly, without any custom code. Would be way nicer.
This issue has been fixed in Nx directly:
https://github.com/nrwl/nx/blob/3d9bd16ce0f322e28e082bbb09f73069310ed6f2/packages/nx/src/tasks-runner/task-env.ts#L186-L201