Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set node environment variable to dynamic value in npm script

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?

like image 542
PzYon Avatar asked Sep 04 '18 21:09

PzYon


1 Answers

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"}
like image 109
Michal Biros Avatar answered Oct 26 '22 18:10

Michal Biros