如何在编译时设置电子变量? [英] How do I set an Electron variable at compile time?

查看:82
本文介绍了如何在编译时设置电子变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用电子生成器来打包React应用.我的应用程序使用create-react-app样板.

I am using electron-builder to package a React app. My app uses the create-react-app boilerplate.

有没有办法在编译时设置变量,以便可以在运行时在主进程的代码中有条件地使用它??

Is there a way I can set a variable at compile time, so that it can be used in a conditional within the code in the main process at runtime...?

我正在寻找一个等效于C的预处理器宏.所以我可以做类似的事情:

I'm looking for an equivalent to C's preprocessor macros. So I could do something like:

电子生成器--extraConfig BUILD_TYPE =测试

然后在我的main.js中:

Then in my main.js:

if(extraConfig.BUILD_TYPE ==='testing'){//做些事情>

推荐答案

我将 electron-builder 命令放入NPM脚本中,然后预先运行另一个脚本来设置 BUILD_TYPE 放在 .txt 文件中.

I'd put the electron-builder command in an NPM script, then run another script beforehand to set BUILD_TYPE in a .txt file.

赞:

package.json :

"scripts": {
    "distProd": "node ./setBuildType.js prod && electron-builder",
    "distDev": "node ./setBuildType.js dev && electron-builder",
}

然后在 setBuildType.js 中:

// process.argv[2] Contains the type.
fs.writeFile('./BUILD_TYPE.txt', process.argv[2], function (errObj) {
    if (errObj) {
        console.log(errObj);
    }
});

然后从您的应用中,通过以下方式获取 BUILD_TYPE :

Then from your app, get BUILD_TYPE with:

// Always set `BUILD_TYPE` to `dev` when running from the terminal.
if (!app.isPackaged) {
    var BUILD_TYPE = fs.readFileSync('./BUILD_TYPE.txt');
} else {
    var BUILD_TYPE = 'dev';
}
console.log(BUILD_TYPE); // Outputs "prod" or "dev".

这将检查它是从安装程序运行还是从终端运行,如果是从终端运行,则它将始终将 BUILD_TYPE 设置为 dev .

That'll check if it's running from an installer or from the terminal, if it's running from the terminal then it'll always set BUILD_TYPE to dev.

这篇关于如何在编译时设置电子变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆