Put env file while building in electron packed app
Asked Answered
O

1

2

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?

Obcordate answered 17/6, 2022 at 9:7 Comment(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.Deservedly
O
2

dotenvExpand did the trick.

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

if (process.resourcesPath) {
    dotenvExpand.expand(dotenv.config({ path: path.join(process.resourcesPath, ".env") }));
}
Obcordate answered 5/6, 2023 at 7:48 Comment(5)
Isn't dotenv enough?Deservedly
How did you make sure that the .env file was in the resourcesPath?Deservedly
@Deservedly 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.Obcordate
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. "). dotenv-expand allows you to include env vars within your env vars for example FOO=$BAR.Deservedly
this did the trickInconclusive

© 2022 - 2024 — McMap. All rights reserved.