0

I have dotenv installed in my cypress project and variables in .env file, which looks like this:

USER=Admin 

Is there a way for me to use my env variable USER inside of the npm scripts?

  "scripts": {
    "cypress:open": "npx cypress open --env grepTags=USER"
  },
  • Check: https://stackoverflow.com/questions/34650527/how-to-use-environment-variables-in-package-json and https://stackoverflow.com/questions/22312671/setting-environment-variables-for-node-to-retrieve/57509175#57509175 does that helps? – davidmpaz Jun 30 '22 at 19:42
  • 1
    Does this answer your question? [How to get environment variable in npm script?](https://stackoverflow.com/questions/40022474/how-to-get-environment-variable-in-npm-script) – smac89 Jun 30 '22 at 20:35
  • Unfortunately, existing solutions didn't work for me. This article did: https://www.genui.com/resources/env-variables-json – Valeria Chernikova Jul 06 '22 at 15:30

3 Answers3

0

You can add the env variable right before the npx execution script, e.g.,

USER=adming npx cypress open ...

Note that this will only be applied during the execution of the command and will not stay in the shell. It's a way to temporarily add an env variable while keeping the shell clean.

If you'd like it to be reused, you could do something like the following which stays live for future executions in the same shell. So the use-case is a bit different.

export USER=adming && npx cypress open ...

Behnam Kamrani
  • 739
  • 7
  • 15
0

To use the environment variables defined in the .env file you need to prefix them with process.env

In your case, you can use the USER environment variable like this:

"scripts": {
  "cypress:open": "npx cypress open --env grepTags=${process.env.USER}"
},
user9847788
  • 2,135
  • 5
  • 31
  • 79
-1

I did a bit of searching and found this related StackOverflow thread that may help you: How to use environment variables in package.json

I believe it should be possible to parse the JSON with the fs module, traverse the JavaScript object, insert your env variable in a separate script, and write to the file system the same package.json but with the env variable included. This may be a poor solution though because it will probably need to be run following every change to the contents of the .env file ...

const fs = require("fs");
require("dotenv").config();
const myVar = process.env.MY_ENV_VAR;

let rawJson = fs.readFileSync("package.json");
let parsed = JSON.parse(rawJson);

parsed.scripts.start = myVar; // or whatever string defines your script

let backToJson = JSON.stringify(parsed);
fs.writeFileSync("package.json", backToJson);