Tomaz_
Tomaz_

Reputation: 469

How to set env.development and env.production in Preact app

On react app, you can create .env.production and .env.development and enter different key and values like this.

REACT_APP_API_URL= "xyz"

to pick environment variables automatically based on commands used --> npm start or npm run build.

What is the equivalent process in preact?

Upvotes: 0

Views: 1368

Answers (1)

Mykola Petrychkevych
Mykola Petrychkevych

Reputation: 11

It is my solution

env.js in the root of project:

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;

then create or modify your 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))
      }),
    );
  },
};

Upvotes: 1

Related Questions