Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using environment variables from ~/.bashrc in "npm start"?

Tags:

bash

node.js

npm

Sorry if this is a duplicate. I tried to find a similar question but couldn't. Here's the breakdown:

I need to use a secret key with a package I'm building and I don't want to publish it so I'm trying to set it as a local bash environment variable. In my .bashrc file I have this:

# Obviously this is not the REAL key, just an example
MY_KEY="1111111111111111"

And then in my Gulpfile, I have a task called "dev". For simplicity sake, let's say it looks like this:

gulp.task('dev', function () {
  console.log(process.env.SECRET_KEY);
});

Then, in order to get the secret key into the environment, I have the following in my package.json:

"scripts": {
  "start": "SECRET_KEY=$MY_KEY gulp dev"
}

So the problem is, when I run the command npm start, my gulp task logs undefined for the secret key. But when I manually run the command SECRET_KEY=$MY_KEY gulp dev, the gulp task logs 1111111111111111. So, for some reason, npm start is not correctly accessing my bash variable and passing it into the Node environment. Is there a way to make this work?

like image 684
rescuecreative Avatar asked Aug 09 '16 16:08

rescuecreative


People also ask

Where do I put environment variables in Bashrc?

In order to set a permanent environment variable in Bash, you have to use the export command and add it either to your “. bashrc” file (if this variable is only for you) or to the /etc/environment file if you want all users to have this environment variable.

How do I add variables to npm?

Search for Environment Variables in the Windows search. "Edit the System environment variables" option will be popped in the result. Open that, select the "Path" and click on edit, then click "New" add your nodeJS Bin path i.e in my machine its installed in c:\programfiles\nodejs\node_modules\npm\bin.

How do I pass an environment variable in Bash script?

Environment Variables Bash scripts can also be passed with the arguments in the form of environment variables. This can be done in either of the following ways: Specifying the variable value before the script execution command. Exporting the variable and then executing the script.


1 Answers

This just creates a shell variable, not an environment variable:

MY_KEY="1111111111111111"

To export that shell variable into the environment:

export MY_KEY
like image 127
Charles Duffy Avatar answered Oct 11 '22 11:10

Charles Duffy