This happens in a particular context, I don’t recommend it, but I deal with it, and maybe if you fall here, you too.
I have a React app wrapped into Symfony with Webpack Encore. This issue can be extended to other javascript frameworks.
I’ve been looking for a way to use my env variables in React as well as in Symfony.
I use the basic .env as a .env.sample but with default values. I have .env.local, .env.{env_type} and even .env.{env_type}.local to fit my environment. In addition, they are not mandatory, developers can create or not these env files.
I also need to keep most of my variables private, so out of React but only on Symfony.
0
To do that, I have applied the following updates into webpack.config.js.
By convention, I used the “REACT_APP_” pattern to differentiate between variables accessible from the front and private ones.
const Encore = require('@symfony/webpack-encore');
const dotenv = require('dotenv');
const fs = require('fs');
// ...
Encore.
// ...
.configureDefinePlugin(options => {
const env = dotenv.config({ path: getEnvPaths() });
if (env.error) {
throw env.error;
}
Object.entries(env.parsed).forEach(([key, value]) => {
if (key.startsWith('REACT_APP_')) {
options['process.env.' + key] = JSON.stringify(value);
}
});
})
//...
;
function getEnvPaths() {
let envmode = '';
switch (process.env.NODE_ENV) {
case 'production':
envmode = 'prod';
break;
case 'test':
envmode = 'test';
break;
// case 'development':
default:
envmode = 'dev';
}
return [`.env.${envmode}.local`, '.env.local', `.env.${envmode}`, '.env'].filter(
fileExists
);
}
function fileExists(filePath) {
try {
return fs.statSync(filePath).isFile();
} catch (err) {
return false;
}
}
JSON.stringify() is surprisingly important, because otherwise the process.env.VALUES is considered as a variable name and not a value.