To utilize environment variables in the package.json script through .env, follow these steps:
Install the dotenv
package using npm install dotenv
Create a .env
file at the root of your project directory
Add the necessary environment variables to the .env
file in the format KEY=VALUE
In your package.json
file, create a script that uses the environment variables. For example:
"scripts": {
"start": "node index.js",
"env-example": "node -r dotenv/config index.js"
}
The "env-example"
script loads the .env
file using the dotenv
package before running index.js
.
npm run env-example
. The script will now have access to the environment variables defined in the .env
file.Asked: 2022-08-25 11:00:00 +0000
Seen: 12 times
Last updated: Nov 20 '21