3

How can I pass NODE_ENV into npm run command as parameter?

Example package.json file:

NODE_ENV=8080

...
    "script": {
        "start": "http-server --port $NODE_ENV" // or something similar that
    }
...

Note that NODE_ENV is set by another process, the npm run only can be read from it.

I met this problem when deploying my app into heroku (they will automatically set NODE_ENV). I found another solution for this problem on heroku but I still wanna to know if there is a way to pass NODE_ENV into npm run command.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
namgold
  • 1,009
  • 1
  • 11
  • 32

2 Answers2

3

Environment variables can be used directly, as you have tried to do:

{
  "scripts": {
    "start": "echo $FOO"
  }
}

yarn start and npm run start will both echo the value of the FOO environment variable if you run this start script. I think you have two other problems.

First, you are trying to use the environment variable NODE_ENV to set the port your application listens on. Heroku provides this value via the PORT environment variable, not NODE_ENV. NODE_ENV will contain something like production.

Second, you are trying to set an environment variable in your package.json. This is possible, but it will override the value Heroku sets. Instead, consider using a .env file in development. Its contents can look something like this:

PORT=8080

You'll need tooling to load this file and populate your environment. dotenv is a popular choice. Note that your .env file should not be committed, so consider also adding it to your .gitignore.

There are other methods to set environment variables in your development environment, and any of them will work if you prefer.

Putting this all together, your package.json should contain something like

{
  "scripts": {
    "start": "http-server --port $PORT"
  }
}
ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
  • 1
    My fault was think of port value is set by `$NODE_ENV` instead of `$PORT`. So using `"http-server --port $PORT"` instead of `"http-server --port $NODE_ENV"` fix my problem. Thank you. – namgold Jan 21 '21 at 17:01
-3

You are trying to accept value inside string in double quotes which is wrong. You can access in the following ways:

Option 1: You need to concat two strings.

NODE_ENV=8080

"script": {
    "start": "http-server --port "+NODE_ENV
}

Option 2: You can use template literals

NODE_ENV=8080

"script": {
    "start": `http-server --port ${NODE_ENV}`
}

In Option 2 NODE_ENV will be replaced with the actual value of the variable

Darshan Jain
  • 239
  • 5
  • 14
  • 3
    Please note that this is `package.json` file, not javascript file so you can not write javascript code here. So either concat string or template literals not work – namgold Jan 14 '21 at 03:57
  • Have you added the NODE_ENV to environment variables? Because the structure is the same I tried with different variables – Darshan Jain Jan 14 '21 at 04:17