Set node environment variable to dynamic value in npm script

PzYon picture PzYon · Sep 4, 2018 · Viewed 8.4k times · Source

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?

Answer

Michal Biros picture Michal Biros · Mar 21, 2019

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"}