Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To utilize environment variables in the package.json script through .env, follow these steps:

  1. Install the dotenv package using npm install dotenv

  2. Create a .env file at the root of your project directory

  3. Add the necessary environment variables to the .env file in the format KEY=VALUE

  4. 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.

  1. Run the script using npm run env-example. The script will now have access to the environment variables defined in the .env file.