I would like to set an environment variable dynamically in an npm script.
I'm using cross-env
as I'm developing on Windows and the server is Unix-based. I want to initialize an environment variable with the current date (new Date()
) so I can access and render it in my create-react-app
:
This works (hard-coded string):
"scripts": {
"start": "cross-env-shell REACT_APP_BUILD_DATE=\"currentDate\" react-scripts-ts start",
}
Obviously, currentDate
shouldn't be a string but the result of following expression: new Date()
.
How can I achieve that? In other words: How can evaluate some regular JavaScript and use its result an npm script? Or is this not possible?
I am using simple node script for passing environment variables into called script. It uses child_process.execSync.
// File name: ./build.js
/* eslint-env node */
const execSync = require('child_process').execSync;
const env = Object.create(process.env);
env.REACT_APP_BUILD_DATE= Date.now();
console.log('Used env variables: ' + JSON.stringify(env));
console.log('Run command: react-scripts start');
execSync('react-scripts-ts start', { env: env, stdio: 'inherit' });
Update start command in package.json scripts. like this:
"scripts": {"start": "node ./build.js"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With