【问题标题】:How to set env.development and env.production in Preact app如何在 Preact 应用中设置 env.development 和 env.production
【发布时间】:2022-11-21 05:29:16
【问题描述】:

在 React 应用程序上,您可以创建 .env.production 和 .env.development 并像这样输入不同的键和值。

REACT_APP_API_URL= "xyz"

根据使用的命令自动选择环境变量 --> npm startnpm run build

preact 中的等效过程是什么?

【问题讨论】:

  • React 和 Preact 只是 UI 库。如何设置环境变量取决于您使用的构建工具。没有这些信息无法回答。
  • @rschristian 我正在使用 webpack。
  • 然后它只是标准的节点行为。它不会接收这些文件中的任何一个。你需要自己处理。

标签: preact


【解决方案1】:

这是我的解决方案

环境.js在项目的根目录中:

import fs from 'fs';
import dotenv from 'dotenv';

function getAppEnvironment() {
    const prefix = "PREACT";
    return Object.keys(process.env)
        .filter((key) => new RegExp(`^${prefix}_`, 'i').test(key))
        .reduce((env, key) => {
            env[key] = process.env[key];
            return env;
        }, {});
}

function resolveFile(file) {
    const path = fs.realpathSync(process.cwd());
    return `${path}/${file}`;
}

function getEnvFiles(production) {
    const key = production ? 'production' : 'development';
    return [
        resolveFile(".env"),
        resolveFile(".env.local"),
        resolveFile(`.env.${key}`),
        resolveFile(`.env.${key}.local`),
    ].filter(Boolean);
}


export function getEnvironment(production) {
  const dotenvFiles = getEnvFiles(production);
  dotenvFiles.forEach((dotenvFile) => {
    if (fs.existsSync(dotenvFile)) {
            dotenv.config({
                path: dotenvFile,
                override: true
            })
    }
  });
  return getAppEnvironment();
}

export default getEnvironment;

然后创建或修改你的preact.config.js:

import getEnvironment from './env';

export default {
  plugins: [],
  webpack(config, env, helpers) {
    config.plugins.push(
      new helpers.webpack.DefinePlugin({
        'process.env': JSON.stringify(getEnvironment(env.production))
      }),
    );
  },
};

【讨论】: