Skip to content

Commit

Permalink
chore: update checkEnv.js to rename env vars for Vite if necessary
Browse files Browse the repository at this point in the history
  • Loading branch information
aqandrew committed Sep 26, 2024
1 parent 0486bd4 commit f101db3
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion utils/checkEnv.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const dotenv = require('dotenv');

const red = '\x1b[31m%s\x1b[0m';
const green = '\x1b[32m%s\x1b[0m';
const vitePrefix = 'VITE_';

const envPath = path.resolve(__dirname, '../.env');
const exampleEnvPath = path.resolve(__dirname, '../.example.env');
Expand All @@ -23,7 +24,28 @@ function getEnv(fileName) {
if (fs.existsSync(envPath)) {
const env = getEnv(envPath);
const exampleEnv = getEnv(exampleEnvPath);
const missingKeys = Object.keys(exampleEnv).filter(key => !Object.keys(env).includes(key));
const envKeys = Object.keys(env);
let missingKeys = Object.keys(exampleEnv).filter(key => !envKeys.includes(key));
const keysToRenameForVite = envKeys.filter(key =>
missingKeys.some(missingKey => missingKey === vitePrefix + key)
);

// for variables that client-side code needs to access, ensure their names begin with `VITE_`
// https://vitejs.dev/guide/env-and-mode.html#env-files
if (keysToRenameForVite.length > 0) {
console.log('These keys in your .env file are not compatible with Vite:', keysToRenameForVite, '\n');
console.log('Renaming incompatible keys...');
let envText = fs.readFileSync(envPath, 'utf8');
keysToRenameForVite.forEach(key => envText = envText.replace(key, vitePrefix + key));
fs.writeFileSync(envPath, envText)
console.log(green, `File updated: ${envPath}\n`);
}

missingKeys = missingKeys.filter(key =>
!keysToRenameForVite
.map(missingViteKey => vitePrefix + missingViteKey)
.includes(key)
);

if (missingKeys.length > 0) {
console.log('You are missing these keys in your .env file:', missingKeys, '\n');
Expand Down

0 comments on commit f101db3

Please sign in to comment.