How Can I set environment variables into the executable electron forge build?
Asked Answered
D

1

7

I'm building an Electron app using Electron Forge and I need to pass environment variables to the final executable.

I've tried defining the environment variables in forge.config.js like this:

env: {
  DB_PATH_RELATIVE: process.env.DB_PATH_RELATIVE,
  DB_CURRENT_VERSION: process.env.DB_CURRENT_VERSION
}

But the environment variables don't seem to be passed to the final executable. I've also tried setting the environment variables using cross-env in the start and make scripts in package.json, but that doesn't seem to work either, just are accesible from forge.config.js only seem to be accessible within that file and are not passed to the final executable.

What's the correct way to pass environment variables to the final executable of an Electron Forge app? Any help would be appreciated. Thanks!

Deliladelilah answered 4/5, 2023 at 21:10 Comment(2)
Did you ever figure out a resolution to this problem?Blinding
No. I ended up making a script to run after the build that hardcoding my variables into the bundle file builded =(Deliladelilah
F
0

This sheds some light on a solution: https://github.com/electron/forge/issues/442#issuecomment-368736955

In the package.json:

"scripts": {
  "make": "APP_ENV=staging electron-forge make",
  // other
 },

Since I use asar=true in the forge config, I needed to add the json file as an extra resource, resulting in this config:

// forge.config.ts
module.exports = {
  packagerConfig: {
      asar: true,
      extraResource: [path.resolve(__dirname, "./env.json")],
      // other options
  },
  hooks: {
    generateAssets: async () => {
      fs.writeFileSync(
        './env.json',
        JSON.stringify({
          role: process.env.MY_APP_ROLE // here the env variable is saved to file
        })
      );
    }
  }
}

and then in the code, e.g. main.ts:

const pathToJson = path.join(__dirname, "..", "..", "..", "./env.json");
const data = fs.readFileSync(pathToJson, "utf8");
const APP_ENV = JSON.parse(data).APP_ENV;

The path here probably strongly depends on your setup. That's just how it looks for me. If you don't use asar, the approach is probably a bit different, more like described in the github answer.

Fore answered 19/6 at 10:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.