npm run with NODE_ENV as parameter

Viewed 277

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.

2 Answers

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"
  }
}

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

Related