'How can I change Environments variables in Electron between production and stage [duplicate]

I want to change API URL depending on the environments. for example

production: https://example.com
stage: https://stage.example.com
local: https://localhost:3001

In Electron, How can I set Environment variables?

I tried to change production name when I build but it was useless



Solution 1:[1]

With node you can use process.env.

In your code:

if(process.env.NODE_ENV === 'production') {
 // use production api
 const api = 'https://example.com';
}

or use a switch case:

switch (process.env.NODE_ENV) {
 case 'production':
  // use production api
  const api = 'https://example.com';
  break;
 case 'stage':
  // use stage api
  const api = 'https://stage.example.com';
  break;
 case 'local':
  // use local api
  const api = 'https://localhost:3001';
  break;
 default:
  // use a default this api
}

And in your terminal when using Electron:

$ NODE_ENV=production electron index.js

Or add it as script in your Package.json

"production": "NODE_ENV=production electron index.js",
"stage": "NODE_ENV=stage electron index.js",
"local": "NODE_ENV=local electron index.js"

Then you can use it:

$ npm run production
$ npm run stage
$ npm run local

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gert-Jan Wille