env variables handling
This commit is contained in:
111
js/env-loader.js
111
js/env-loader.js
@@ -1,80 +1,56 @@
|
||||
// env-loader.js
|
||||
// This module is responsible for loading environment variables from .env file
|
||||
// This module is responsible for loading environment variables for the PWA
|
||||
|
||||
// Store environment variables in a global object
|
||||
window.ENV_CONFIG = {};
|
||||
window.ENV_CONFIG = {
|
||||
// Default values that will be overridden when config.env.js loads
|
||||
PUBLIC_VAPID_KEY: 'your_public_vapid_key_here',
|
||||
BACKEND_URL: 'https://your-push-server.example.com'
|
||||
};
|
||||
|
||||
// Function to load environment variables from .env file
|
||||
// Function to load environment variables from config.env.js
|
||||
async function loadEnvVariables() {
|
||||
try {
|
||||
// Fetch the .env file as text
|
||||
const response = await fetch('/.env');
|
||||
// Try to fetch the config.env.js file which will be generated at build time or deployment
|
||||
const response = await fetch('/config.env.js');
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn('Could not load .env file. Using default values.');
|
||||
setDefaultEnvValues();
|
||||
console.warn('Could not load config.env.js file. Using default values.');
|
||||
return;
|
||||
}
|
||||
|
||||
const envText = await response.text();
|
||||
const configText = await response.text();
|
||||
|
||||
// Parse the .env file content
|
||||
const envVars = parseEnvFile(envText);
|
||||
|
||||
// Store in the global ENV_CONFIG object
|
||||
window.ENV_CONFIG = { ...window.ENV_CONFIG, ...envVars };
|
||||
|
||||
console.log('Environment variables loaded successfully');
|
||||
// Extract the configuration object from the JavaScript file
|
||||
// The file should be in format: window.ENV_CONFIG = { key: "value" };
|
||||
try {
|
||||
// Create a safe way to evaluate the config file
|
||||
const configScript = document.createElement('script');
|
||||
configScript.textContent = configText;
|
||||
document.head.appendChild(configScript);
|
||||
document.head.removeChild(configScript);
|
||||
|
||||
console.log('Environment variables loaded successfully from config.env.js');
|
||||
|
||||
// Dispatch an event to notify that environment variables have been loaded
|
||||
window.dispatchEvent(new CustomEvent('env-config-loaded', {
|
||||
detail: { config: window.ENV_CONFIG }
|
||||
}));
|
||||
} catch (parseError) {
|
||||
console.error('Error parsing config.env.js:', parseError);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading environment variables:', error);
|
||||
setDefaultEnvValues();
|
||||
}
|
||||
}
|
||||
|
||||
// Parse .env file content into key-value pairs
|
||||
function parseEnvFile(envText) {
|
||||
const envVars = {};
|
||||
|
||||
// Split by lines and process each line
|
||||
envText.split('\n').forEach(line => {
|
||||
// Skip empty lines and comments
|
||||
if (!line || line.trim().startsWith('#')) return;
|
||||
|
||||
// Extract key-value pairs
|
||||
const match = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/);
|
||||
if (match) {
|
||||
const key = match[1];
|
||||
let value = match[2] || '';
|
||||
|
||||
// Remove quotes if present
|
||||
if (value.startsWith('"') && value.endsWith('"')) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
|
||||
envVars[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
return envVars;
|
||||
}
|
||||
|
||||
// Set default values for required environment variables
|
||||
function setDefaultEnvValues() {
|
||||
window.ENV_CONFIG = {
|
||||
...window.ENV_CONFIG,
|
||||
PUBLIC_VAPID_KEY: 'your_public_vapid_key_here',
|
||||
BACKEND_URL: 'https://your-push-server.example.com'
|
||||
};
|
||||
console.log('Using default environment values');
|
||||
}
|
||||
|
||||
// Export function to initialize environment variables
|
||||
export async function initEnv() {
|
||||
await loadEnvVariables();
|
||||
return window.ENV_CONFIG;
|
||||
}
|
||||
|
||||
// Auto-initialize when imported
|
||||
// Start loading environment variables immediately
|
||||
initEnv();
|
||||
|
||||
// Export access functions for environment variables
|
||||
@@ -82,7 +58,30 @@ export function getEnv(key, defaultValue = '') {
|
||||
return window.ENV_CONFIG[key] || defaultValue;
|
||||
}
|
||||
|
||||
// Export a function to wait for environment variables to be loaded
|
||||
export function waitForEnv() {
|
||||
return new Promise((resolve) => {
|
||||
// If we already have non-default values, resolve immediately
|
||||
if (window.ENV_CONFIG.BACKEND_URL !== 'https://your-push-server.example.com') {
|
||||
resolve(window.ENV_CONFIG);
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, wait for the env-config-loaded event
|
||||
window.addEventListener('env-config-loaded', (event) => {
|
||||
resolve(event.detail.config);
|
||||
}, { once: true });
|
||||
|
||||
// Set a timeout to resolve with current values if loading takes too long
|
||||
setTimeout(() => {
|
||||
console.warn('Environment loading timed out, using current values');
|
||||
resolve(window.ENV_CONFIG);
|
||||
}, 3000);
|
||||
});
|
||||
}
|
||||
|
||||
export default {
|
||||
initEnv,
|
||||
getEnv
|
||||
};
|
||||
getEnv,
|
||||
waitForEnv
|
||||
};
|
||||
Reference in New Issue
Block a user