首页 > 解决方案 > Electron - 重启应用程序/刷新环境变量

问题描述

我目前正在开发一个使用第三方软件的 Electron 应用程序。在某些时候,我正在检查该软件是否安装在用户的计算机上(它必须在 PATH 中),如果它不存在,我就运行安装。正如我所说,安装会将一个目录附加到 PATH 变量中。发生这种情况后,我需要重新启动应用程序才能访问更新的变量。

我已经尝试使用relaunch,就像在文档中一样,但它不会刷新变量:

app.relaunch()
app.exit(0)

如果我手动重新启动应用程序,那么一切正常。

有人有什么想法吗?谢谢。

标签: environment-variableselectron

解决方案


我的解决方案只适用于生产:

在生产中,您的应用程序无法获取您 PC 的环境变量。因此,当您在 main.js 中创建 mainWindow 时,您应该读取环境变量并将其传递给 process.env 变量。重新启动应用程序后,它将按照您的预期再次重新加载 env。

正在使用的图书馆:

https://github.com/sindresorhus/shell-env

https://github.com/sindresorhus/shell-path

import shellEnv from 'shell-env';
import os from 'os';
import shellPath from 'shell-path';

const isDevelopment = process.env.NODE_ENV === 'development';

function createMainWindow() {
  mainWindow = new BrowserWindow({
    webPreferences: {
      nodeIntegration: true,
    },
    width: 800,
    height: 1000,
  });

  // ...

  if (!isDevelopment) {
    // TODO: if we're running from the app package, we won't have access to env vars
    // normally loaded in a shell, so work around with the shell-env module
    // TODO: get current os shell
    const { shell } = os.userInfo();

    const decoratedEnv = shellEnv.sync(shell);

    process.env = { ...process.env, ...decoratedEnv };

    console.log('DEBUG process.env', process.env);

    // TODO: If we're running from the app package, we won't have access to env variable or PATH
    // TODO: So we need to add shell-path to resolve problem
    shellPath.sync();
  }

  // ...
}

重新启动应用程序后,环境变量将被更新。

app.relaunch()
app.exit(0)

注意:如果不勾选!isDevelopment,重新启动后,应用程序将不会显示。我不知道。


推荐阅读