您可以在电子生产中使用dotenv吗?

发布于 2025-02-09 13:56:26 字数 270 浏览 1 评论 0 原文

我正在构建一个电子,React应用程序,其中我需要一个 dotenv 文件。 在代码中,我使用 process.env.variable 调用我的变量,该变量在开发中正常。

但是,一旦用电子构建器分发, dotenv变量不再工作( undefined )。

我现在的问题是,甚至可以这样做,如果是,如何?我试图在互联网上找到解决方案,但似乎人们并没有真正面临这个问题。

I'm building an Electron, React app where I'm in need of a dotenv file.
In code, I call my variables with process.env.variable which works fine in development.

However, once distributed with electron-builder, the dotenv variables no longer work (undefined).

My question is now, is it even possible to do this and if yes, how? I tried to find a solution in the internet but it seems like people don't really face this issue.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一个人的夜不怕黑 2025-02-16 13:56:26

不确定这个问题是否仍然有效,但这是我得到的,以防有人有同样的问题。如果您使用的是电子构建器,目前尚不在本地支持。

envs不会在分布式中加载,因为电子构建器是包装器,而不是捆绑器。 ENV仅用于配置包装步骤的负载。
(来自Eletron-Builder合作者)

但这并不意味着没有其他方法,这是我对此的肮脏方式,我创建了一个脚本来替换用于电子构建器构建-Publish 。

我正在使用React样板,在您受尊敬的框架上可能有所不同。因此,我创建一个脚本来替换 app/dist/main/main.js 在WebPack完成将我的TS转换为JS文件时,它应该就在 Eletron-Builder << /code> bash行被执行。

这是我所做的事情的详细信息:

文件夹结构

app
    scripts(self-created)
          packageEnv.js
    ...

package.json

"scripts": {
    "build": "concurrently \"npm run build:main\" \"npm run build:renderer\"",
    "package:env": "node ./scripts/packageEnv.js",
    "build:main": "cross-env NODE_ENV=production TS_NODE_TRANSPILE_ONLY=true webpack --config ./.erb/configs/webpack.config.main.prod.ts",
    "build:renderer": "cross-env NODE_ENV=production TS_NODE_TRANSPILE_ONLY=true webpack --config ./.erb/configs/webpack.config.renderer.prod.ts",
    "package": "ts-node ./.erb/scripts/clean.js dist && npm run build && npm run package:env && electron-builder build --publish never",
    "rebuild": "electron-rebuild --parallel --types prod,dev,optional --module-dir release/app",
  },

package> package> packageenv.js 的代码(超级肮脏,我建议阅读和重构它)。也放置了一些 todo

const fs = require('fs');

const splitLineIntoPairs = (line) => {
  const firstEqualSymbolPosition = line.search('=');
  const key = line.slice(0, firstEqualSymbolPosition).replaceAll(' ', '');
  const values = line
    .slice(firstEqualSymbolPosition + 1, line.length)
    .replaceAll(' ', '');
  return {
    key,
    values,
  };
};

const createEnvObj = (envByLines) => {
  return envByLines.map((line) => {
    const { key, values } = splitLineIntoPairs(line);
    return {
      key,
      values,
    };
  });
};

const writeEnvToDistApp = ({ path, env }) => {
  // TODO: Should make it so that the code read by chunks instead of loading entire file, may encounter memory shortage if file too big atm
  let mainJs = fs.readFileSync(path).toString();
  env.forEach(({ key, values }) => {
    // TODO: Replace with your env variable template
    mainJs = mainJs.replace(`process.env.${key}`, `"${values}"`);
  });
  fs.writeFileSync(path, mainJs);
};

const packageEnv = () => {
  const envFileContent = fs.readFileSync('./.env').toString();
  const envByLines = envFileContent.split('\n').filter((line) => {
    return line !== '';
  });
  const envObj = createEnvObj(envByLines);
  writeEnvToDistApp({
    // TODO: Replace with your release app structure
    path: './release/app/dist/main/main.js',
    env: envObj,
  });
};

packageEnv();

Not sure if this question is still valid, but here is what I got in case anyone has the same question. If you are using electron-builder, this is not supported natively at the moment.

ENVS don't load in the distributable, as electron-builder is a packager, not a bundler. ENVs only load for configuring the packaging step.
(From eletron-builder collaborator)

https://github.com/electron-userland/electron-builder/issues/7143

But that does not mean there aren't any other way around, here is my dirty way of work around on this, I created a script to replace the env placeholder used for electron-builder build --publish.

I'm using React boilerplate, it might be different on yours respected framework. So I create a script to replace env in the app/dist/main/main.js when the webpack finished transpiling my TS to JS files, it should be right before the eletron-builder bash line got executed.

Here is a detailed of what I did:

Folder structure

app
    scripts(self-created)
          packageEnv.js
    ...

package.json:

"scripts": {
    "build": "concurrently \"npm run build:main\" \"npm run build:renderer\"",
    "package:env": "node ./scripts/packageEnv.js",
    "build:main": "cross-env NODE_ENV=production TS_NODE_TRANSPILE_ONLY=true webpack --config ./.erb/configs/webpack.config.main.prod.ts",
    "build:renderer": "cross-env NODE_ENV=production TS_NODE_TRANSPILE_ONLY=true webpack --config ./.erb/configs/webpack.config.renderer.prod.ts",
    "package": "ts-node ./.erb/scripts/clean.js dist && npm run build && npm run package:env && electron-builder build --publish never",
    "rebuild": "electron-rebuild --parallel --types prod,dev,optional --module-dir release/app",
  },

Code for packageEnv.js (it's super dirty, I would recommend to read and refactor it). Placed some TODO there as well.

const fs = require('fs');

const splitLineIntoPairs = (line) => {
  const firstEqualSymbolPosition = line.search('=');
  const key = line.slice(0, firstEqualSymbolPosition).replaceAll(' ', '');
  const values = line
    .slice(firstEqualSymbolPosition + 1, line.length)
    .replaceAll(' ', '');
  return {
    key,
    values,
  };
};

const createEnvObj = (envByLines) => {
  return envByLines.map((line) => {
    const { key, values } = splitLineIntoPairs(line);
    return {
      key,
      values,
    };
  });
};

const writeEnvToDistApp = ({ path, env }) => {
  // TODO: Should make it so that the code read by chunks instead of loading entire file, may encounter memory shortage if file too big atm
  let mainJs = fs.readFileSync(path).toString();
  env.forEach(({ key, values }) => {
    // TODO: Replace with your env variable template
    mainJs = mainJs.replace(`process.env.${key}`, `"${values}"`);
  });
  fs.writeFileSync(path, mainJs);
};

const packageEnv = () => {
  const envFileContent = fs.readFileSync('./.env').toString();
  const envByLines = envFileContent.split('\n').filter((line) => {
    return line !== '';
  });
  const envObj = createEnvObj(envByLines);
  writeEnvToDistApp({
    // TODO: Replace with your release app structure
    path: './release/app/dist/main/main.js',
    env: envObj,
  });
};

packageEnv();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文