electronelectron-builderelectron-packager

Put env file while building in electron packed app


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:

electron-builder --mac --publish never

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


Solution

  • dotenvExpand did the trick.

    const dotenvExpand = require("dotenv-expand");
    
    if (process.resourcesPath) {
        dotenvExpand.expand(dotenv.config({ path: path.join(process.resourcesPath, ".env") }));
    }