Friday, August 19, 2022

[FIXED] How to use env variables in npm scripts?

Issue

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


Solution

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'



Answered By - Andrei
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.