Ali*_*lin 5 environment-variables electron
我目前正在开发一个使用第三方软件的 Electron 应用程序。在某些时候,我会检查该软件是否安装在用户的计算机上(它必须在 PATH 中),如果没有,我就运行安装。正如我所说,安装会在 PATH 变量中附加一个目录。发生这种情况后,我需要重新启动应用程序才能访问更新的变量。
我已经尝试使用relaunch,就像在文档中一样,但它不会刷新变量:
app.relaunch()
app.exit(0)
Run Code Online (Sandbox Code Playgroud)
如果我手动重新启动应用程序,则一切正常。
有没有人有一些想法?谢谢。
我的解决方案仅适用于生产:
在生产中,您的应用程序无法获取 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();
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
重新启动应用程序后,环境变量将被更新。
app.relaunch()
app.exit(0)
Run Code Online (Sandbox Code Playgroud)
注意:如果不勾选!isDevelopment,重新启动后,应用程序将不会显示。我不知道。
| 归档时间: |
|
| 查看次数: |
1531 次 |
| 最近记录: |