npm / run-script and environment variables

I'm having problems running npm tasks with environment variables. I have right clicked on the task and in the Edit Run/Debug configuration: 'start' dialog added my environment variable, but when I go to execute the 'start' task within my script the environment variable I set is undefined when accessed via process.env.VARIABLE_NAME. 

If I set up a Node.js configuration specifically to do the same as my npm 'start' task then the environment variables I set there DO get passed to the executing process, and are available in process.env.VARIABLE_NAME - however, there's often more complex tasks in npm that I just can't set up as Node.js Run/Debug configurations.

Just wondering if there's some sort of configuration option that I'm maybe missing...

2
6 comments

This is very strange... I couldn't get it going for the life of me before, but now it's working. I don't even know what has changed.

0

Hi!

I think I have the same issue, with my react frontend.

I set up the run/debug config: 

set up the debug in the script/component:

The result in the browser console (undefined): 

 

If I run a vanilla Node project, configured the run/debug,

and ran the same lines in a script. it works fine and logs the string in the console.

0
  1. The variable should be prefixed with REACT_APP_

    eg: REACT_APP_API_KEY=12345

  2. You need to restart the server to reflect the changes.

  3. No need to wrap your variable value in single or double quotes.

Read more here and the official docs

1

How set environment variable for `npm install` ?

 

0

You can try setting them in a shell prior to starting the command from it

Adding variables to .npmrc placed into the root of the project should also work

0

Please sign in to leave a comment.