1

I need to put a .env file into a packed app while building, then attach variables from the .env to process.env. I put the .env in the same directory as the package.json and it works when I start electron from npm. It won't work when I build a MacOS app and start it (it seems as though the .env file is lost).

My main.js starts a java backend, so I provide environment variables:

// This works in npm start, but not for packed app
process.env.MY_VAR = dotenv.config().parsed.MY_VAR;

this.serverProcess = require("child_process").spawn(
    "/usr/bin/env",
    ["sh", dirname + "/server/bin/embedded"],
    { env: process.env });

My case is:

  • Generate .env and put it to electron folder (it generates automatically by build system)
  • Build electron and pack electron
electron-builder --mac --publish never
  • Start MacOS App
  • Packed app should run java with the provided environment (from .env)

Is there an example or best practices how to put environmental variables while package building?

icc97
  • 11,395
  • 8
  • 76
  • 90
Komdosh
  • 340
  • 3
  • 20
  • 1
    One thing that I have learned is that the `.env` file access is different than for the application `.env` file access. So if I just include a `.env` file in the root of my project next to the `package.json` then it will get picked up in the application. However this still doesn't work for `main.js`. – icc97 Jun 22 '23 at 20:26

1 Answers1

1

dotenvExpand did the trick.

const dotenvExpand = require("dotenv-expand");

if (process.resourcesPath) {
    dotenvExpand.expand(dotenv.config({ path: path.join(process.resourcesPath, ".env") }));
}
Komdosh
  • 340
  • 3
  • 20
  • Isn't `dotenv` enough? – icc97 Jun 21 '23 at 16:39
  • How did you make sure that the `.env` file was in the `resourcesPath`? – icc97 Jun 21 '23 at 16:40
  • @icc97 `dotenv` just loads a file into an object, while `dotenv-expand` loads an object into the environment (`process.env.MY_ENV_VAR`). To avoid unrelated stuff, I'm not checking the existance of `.env` file here. – Komdosh Jun 22 '23 at 07:58
  • 1
    thanks for your reply. `dotenv` does already put the vars into `process.env` ([*"Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. "*](https://github.com/motdotla/dotenv#dotenv-)). `dotenv-expand` allows you to include env vars *within* your env vars for example `FOO=$BAR`. – icc97 Jun 22 '23 at 21:03
  • 1
    Thank you for your explanation, that's really make sense – Komdosh Jun 23 '23 at 09:37