Home > Back-end >  How to use env variables in npm scripts?
How to use env variables in npm scripts?

Time:07-10

I am trying to use env variable form file in package.json. All this commands return message "Unbound variable $NODE_ENV"

"scripts": {
  "xxx1": "dotenv -e ../.env echo $NODE_ENV",
  "xxx2": "env-cmd -f ../.env echo $NODE_ENV",
  "xxx3": "NODE_ENV=123 echo $NODE_ENV",
}

../.env:

NODE_ENV=123

${NODE_ENV} return same error. Looks like I do something wrong in the end of command. Help me please

CodePudding user response:

The shell expands the command to dotenv -e ../.env echo before executing it, $NODE_ENV is expanded to empty text because it doesn't have a value yet. The dotenv docs explain this issue: https://github.com/entropitor/dotenv-cli#variable-expansion-in-the-command

This script outputs 123 for me:
dotenv -e ../.env -- bash -c 'echo $NODE_ENV'

  • Related