0

I saw lot of different ways, some looked normal some others looked a bit more patchworked.

Can we use package json script to chose our env variables ? What is the right way to do it with nodeJS and how to do it ?

I have already made an .env. It contains api keys which are global for dev and prod. But I have some variables, the URL variable for exemple, which won't be the same depending on dev or prod.

Here are my scripts in the package.json

 ... "scripts": { "dev": "nodemon app.js", "prod": "node app.js" } 
1
  • I personally prefer not to attach and maintain extra libraries for some trivial tasks that can be achieved with few lines of code and reading key/value pairs from .env file seems to me fairly simple. Commented May 7, 2021 at 12:39

1 Answer 1

1
  1. Use cross-env package to define a NODE_ENV for the command you are running. e.g. "prod": "cross-env NODE_ENV=production node app.js"
  2. In the code, read the env file based on the NODE_ENV config. FWIW dotenv package can help with reading .env files.
Sign up to request clarification or add additional context in comments.

3 Comments

Just a quick note: cross-env is no longer maintained
Thank you both, if cross-env is no longer maintained I guess it's better looking for something else
Well nope, you should use it. It is a reliable tool. The only reason it is not maintained is that the developer won't add new features, but the package does its purpose like a charm, so no worries.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.