@farmfe/core
Version:
Farm is a extremely fast web build tool written in Rust. Farm can start a project in milliseconds and perform HMR within 10ms, making it much faster than similar tools like webpack and vite.
55 lines • 2.09 kB
JavaScript
/**
* The following is modified based on source found in
* https://github.com/vitejs/vite/blob/main/packages/vite/src/node/env.ts
*
* MIT License
* Copyright (c) 2019-present, Yuxi (Evan)
* https://github.com/vitejs/vite/blob/main/LICENSE
*
*/
import fs from 'node:fs';
import path from 'node:path';
import { parse } from 'dotenv';
import { expand } from 'dotenv-expand';
import { arraify, normalizePath, tryStatSync } from '../utils/index.js';
export function loadEnv(mode, envDir, prefixes = ['FARM_', 'VITE_']) {
if (mode === 'local') {
throw new Error(`"local" cannot be used as a mode name because it conflicts with ` +
`the .local postfix for .env files.`);
}
prefixes = arraify(prefixes);
const env = {};
const envFiles = getEnvFilesForMode(mode, envDir);
const parsed = Object.fromEntries(envFiles.flatMap((filePath) => {
if (!tryStatSync(filePath)?.isFile())
return [];
return Object.entries(parse(fs.readFileSync(filePath)));
}));
const processEnv = { ...process.env };
expand({ parsed, processEnv });
// only keys that start with prefix are exposed to client
for (const [key, value] of Object.entries(parsed)) {
if (prefixes.some((prefix) => key.startsWith(prefix))) {
env[key] = value;
}
}
for (const key in process.env) {
if (prefixes.some((prefix) => key.startsWith(prefix)) &&
key !== 'FARM_LIB_CORE_PATH') {
env[key] = process.env[key];
}
}
return env;
}
export function getExistsEnvFiles(mode, envDir) {
const envFiles = getEnvFilesForMode(mode, envDir);
return envFiles.filter((filePath) => tryStatSync(filePath)?.isFile());
}
export function setProcessEnv(mode) {
process.env.NODE_ENV = mode;
}
export const isDisableCache = () => !!process.env.DISABLE_CACHE;
export function getEnvFilesForMode(mode, envDir) {
return [`.env`, `.env.local`, `.env.${mode}`, `.env.${mode}.local`].map((file) => normalizePath(path.join(envDir, file)));
}
//# sourceMappingURL=env.js.map